You should load existing term using term id and then update vid of term from new vocabulary vid then save it.

use Drupal\taxonomy\Entity\Term;

$term = Term::load($tid);
$term->vid->setValue('ID value');
$term->Save();


How to make multiple fields with taxonomy terms?

Try field_collection.  Add one to your form, allowing multiple responses for the field.  Then add term reference, price, and rating fields to the field collection.


How to import Joomla user created date to Drupal?

Drupal uses timestamp for a date.
You could convert it to timestamp using strtotime()

$timestamp = strtotime('2008-08-05 20:20:42.000000');

Now in $timestamp you will have same output as in Drupal db.


No results view filtering on newly added field of content type

You can set the views filter operation to Is not equal to and the value as true.

This should work for new entities that have the value as false and old entities where it just isn't set.


Is it possible to use rules to set user profile pictures?

Create a componnent in rule with this ! On the componnent you have 2 parameters. One for the user and another one for the file you want to use ! I use Drupal 7.

$uid = $user->uid;
$account = user_load($uid);
$thefile = file_load($file->fid);

$edit['picture'] = $thefile;
user_save($account, $edit);

Call the componnent from the rules you want. On my side i'm using a flag to trig the rules. The user mark an image to use it has a profile picture and it work.

I use this link has a starter to create the rule. http://taggartjensen.com/code-snip/drupal-7-set-user-picture-programmatically

Good luck !


Logger will always log for the current user, except you provide your own logging service.

The context is used to replace placeholders in the message, see here, so to get the userid in the message, use this:

\Drupal::logger("proreos")->info("bla @uid", array('@uid' => 5));


Print specific block from a region in drupal 7

You can use this method:

$module = 'my_module'; // This is the module that provides the hook_block_view
$delta = 'my_block'; // you can get $delta from moduel hook_block_info
$block = module_invoke($module, 'block_view', $delta);
print render($block['content']);


How can I delete all field collection revisions?

Since you want to purge revisions on a field in a field collection and not an entire content type, your best bet is going to be doing this directly in phpMyAdmin. I don't know of any modules that enable you to delete revisions for a particular field but not the whole content type.

I would locate the field in question and run DELETE from field_revision_field_yourfieldname.

Of course you should back up things before you run a delete query.

The data for nodes and node revisions are store in two different tables. The data for the node page is stored in field_data_yourfieldname. The data for the revision is stored in field_revision_field_yourfieldname.

To illustrate this concept for you, I set up a fresh install of drupal (7.28) on my local machine and connected it to a new empty database.

I set up a content type called field collection demo and I added two field collections.

Since I'm not sure what your configuration entails, the fields I used may or may not be similar to your fields.

Then I created two sample nodes and edited both of them several times with revision tracking turned on. I mostly used lipsum text but for the last revision I typed meaningful text to help you see what's happening in the database.

Here you see that I have created the two nodes:

Here you can see the lipsum text in the original post.

Here you can see that I've created multiple revisions of the node.

And here you can see the meaningful revised text that is the most recent revision.

The next picture shows you how this data is stored in the database in the field_revision_field_yourfieldname table.

You can manually delete one row from the table using the red "X" in phpMyAdmin. Look, for instance, at the last row in this table.

After I click the red "X" for that row, it is deleted.

You can see that now the revision that began with r2 is gone from the field_revision_field_my_fifth_field table.

This removes the revision from the node's revision page. Notice in this picture, the field labeled "My fifth field" is missing.

But this does not affect the node's public view, because that data is stored in the field_data_my_fifth_field table not in the field_revision_field_my_fifth_field_table.

Therefore, I can safely delete all the revisions from the field_revision_field_my_fifth_field_table with the delete query (as I've done on my demo site) and still view the node with no problems:

All the revisions from the field "My fifth field" are gone on the revisions tab but the view tab remains unchanged.

If you wanted to delete all the revisions for all the fields that comprise a node collection, you would simply run the delete query for each of the field_revision_field_yourfieldname tables in the database.


There is Aegir, which is a system that helps you with doing that.

I personally have no experience with it, but I attended a talk on it a few weeks ago and it totally does the job.

In general, it gives you an admin interface of all your sites on that drupal installation while letting you update each one individually. It automatically rolls back if something fails.

Go have a look: http://www.aegirproject.org/

It probably is overkill with just two or three sites, but it seems to help a lot with bigger sites.


I had a very similar problem and I could solve it using Views Matrix module. It has only a dev version for Drupal 7, but it did the job perfectly.

Look at this question, it's almost the same except that I didn't need to count the items: Matrix view with content as columns and taxonomy terms as rows

There is also another answer to that question which I tested and it works as well.


Is it possible to have multiple instances of the same field in one content type?

No, field instance is unique within a content type. See field_create_instance. Relevant code for checking uniqueness in that function:

// Ensure the field instance is unique within the bundle.
// We only check for instances of active fields, since adding an instance of
// a disabled field is not supported.
$prior_instance = field_read_instance($instance['entity_type'], $instance['field_name'], $instance['bundle']);
if (!empty($prior_instance)) {
  $message = t('Attempt to create an instance of field @field_name on bundle @bundle that already has an instance of that field.', array('@field_name' => $instance['field_name'], '@bundle' => $instance['bundle']));
  throw new FieldException($message);
}


How to validate numbers in a webform custom composite element

Instead of putting validations just create a number type field. And inside the number field of the custom composite element, you can not enter the letters, only numbers can be entered so no concept/need for validating against letters.


Configuring Drupal 6.20 to display a different icon in a specific region on a specific group of pages

If this is being displayed on nodes you can add an imagefield to the content type and set its display settings to excluded. Then make a views block that displays the image field, using a default argument of the current node.


How to block temporarily comments from specific IP address?

I have not used this module but you can check Comment IP module.

  This module displays a comments IP address in the comment overview
  page and allows you the option to "Delete the selected comments and
  block their IP's" from the comment overview dropdown list.


How to restrict a specific user to an IP range he can login from?

Have a look at IP Ranges module.

  IP Ranges is a module that let's you completely ban both single IP-addresses as well as
  full ranges from your site. The ban is triggered already at the early bootstrap phase, so you
  can get rid of unwanted visitors as early as possible without wasting server resources.

  You can also define whitelists that override blacklists, both single and ranged.
  The UI is similar to core ip-ban, so you will feel like home immediately.


Strange characters after URL -> /#.UAfaBbTY-iE

Do you have an AddThis widget on any of the pages?  This is a known issue with that widget.  to resolve change this portion of the snippet:

var addthis_config = {"data_track_addressbar":true};

WITH

var addthis_config = {"data_track_addressbar":false};


How to pass contextual filter to a view pane?

Add another condition to check the specific display name

if($view->current_display == 'display_name')

Here display_name of particular display can be found in Advanced Option -> Machine Name


How do I define a route and controller for the home page?

This is a classic case of trying to do something in the non-Drupal way -- conceptually, defining a custom route for your home page route makes sense, and it's possible in other frameworks, but Drupal has a different way of doing things that makes this approach completely unintuitive.

Here's how to do it:

Define your route as something other than '/' (i.e. '/students/overview')
In /admin/config/system/site-information, set your "Default Front Page" to whatever your route was:

Voila!


Display content type through custom template

this is my method for doing such thing and it always works.

create a view of your content type (ct), say ct__view. create a page and rename it to
 page--path_of_view.tpl.php and embed that view inside it at any where you want with this instruction <?php print views_embed_view('ct__view','page');?>. now you can customize its fields output with views-view-fields--ct__view--page.tpl.php


Get enitity ID after programatically creating one

You can use getIdentifier() method of the wrapper.

$node = entity_create('node', array('type' => 'person'));
$entity = entity_metadata_wrapper('node',  $node);
$entity->save();
$entity->getIdentifier();


Alter views fields using preprocess function before render?

Drupal 7

Either you have to use hook_views_pre_render() or create appropriate TPL file (e.g. views-view-fields--MYVIEW.tpl.php) in your template dir (check Theme:Information in view edit page for more details).

You may also use preprocess theme function to print a single record from a row, with fields which is template_preprocess_views_view_fields().

Related:

_preprocess_views_view__ specify view name
Drupal 7 preprocess_views not working
Specific preprocess functions for theme hook suggestions are not invoked


Fire $.colorbox.resize() after overlay content is AJAX loaded?

Drupal has behaviors for interacting after ajax events.
For more information on drupal javascript see http://drupal.org/node/756722

You should be able to do it using something like this:

(function ($) {

  Drupal.behaviors.yourBehavior = {
    attach: function (context, settings) {
      $(document).bind('cbox_complete', function() {
        setTimeout($.colorbox.resize, 1000);
      });
    }
  };

})(jQuery);

The easiest way to implement this, if you want it in your theme is to put that above code in a script.js file in your theme (you can name that file anything and have as many separate files as you like) then in your info file have

scripts[] = script.js

You can also put it in a js subdirectory and in your info file then put

scripts[] = js/script.js

You can then also put other behaviors in there too.

That will load your javascript on all pages though, which in some cases is desired but in some cases is not.

If you only want it to load on some pages then you call

drupal_add_js('path/to/js/file.js');

from wherever you want to load it.

For example, if you only want it to load on full node pages you could put this in your THEMENAME_preprocess_node() function in your template.php file.

// Only attach this on full node pages.
if (!empty($variables['page'])) {
  drupal_add_js(drupal_get_path('theme', 'THEMENAME') . '/script.js');
}

Or you could do it in a module using something like hook_node_view().


get value from content type B, in a view of content type A

To retrieve information linked through ER fields you have to add the Relationship for the ER field.
The Relationship will open new options you can add to your Views.
You will be able to add the Duration Field to your Views after you add the Relationship. That field will use the Relationship by default (it wouldn't work without it).


Cannot read nodes containing an email address

I'm not sure why you're having trouble with the bundle condition, but as an alternative you could use a propertyCondition and query on the node type instead:

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->propertyCondition('type', 'my_content_type')
  ->fieldCondition('field_user_email_address', "email", $email)
  ->propertyCondition('status', 1);


Is there a way to change edit link for Nodes?

Try out this code. add it to your module

function mymodule_url_outbound_alter(&$path, &$options, $original_path) {
  if (preg_match('|^node/([0-9]*)/edit(/.*)?|', $path, $matches)) {
    if ($node->nid == $matches[1]) {
      $path = 'node/edit/$node->nid' . $matches[2];
    }
  }
}


How to create a list of nodes that the anonymous user has created and limit it by the current session (SID)?

You should be able to use hook_node_insert to grab the nid of the node that is being created. Take the nid and add it to $_SESSION. Then create a View that accepts NIDs as contextual arguments. You'll need to do some additional coding to grab those NIDs from the session and pass it to the View.


If your question pertains to Drupal 7 then you may want to take a look at the Entity Reference Autofill

  The Entity reference autofill module gives Entity reference fields an option to populate other form fields with data from selected referenced entities.


To expand on mojzis's comment:

// Load your data.
$entries = db_query('SELECT * FROM {my_table}')->fetchAll();

// Prepare a header for your table. The array keys will match up to the key used to input rows in a minute. The values are the column headers.
$header = array(
  'title' => 'Entry title',
  'foo' => 'Bar',
  'op' => 'Operations',
);

// Loop through your data and prepare table rows.
$rows = array();
foreach ($entries as $entry) {
  // Prepare your operation links.
  $op_links = array(
    l('view', 'path/to/entry/' . $entry->id),
    l('edit', 'path/to/entry/' . $entry->id . '/edit', array('query' => drupal_get_destination())),
    l('delete', 'path/to/entry/' . $entry->id . '/delete', array('query' => drupal_get_destination())),
  );

  $rows[] = array(
    'title' => $entry->title,
    'foo' => $entry->bar,
    'op' => implode(' ', $op_links),
  );
}

// Prepare the build
$form['existing_entries'] = array(
  '#theme' => 'table',
  '#header' => $header,
  '#rows' => $rows,
  '#empty' => t('No entries have been created.'),
);


Is there any PHP package that's very similar to the Plugin API?

Drupal 8 Plugin API can be installed as a standalone package like follows:
composer require drupal/core-plugin
To make use of it you will have to develop a bunch of integration code.
Unfortunately there is no much documentation on how to use Drupal components without Drupal core.


If you are using Features module in Drupal 7 to deploy the rules. You will get an overriden or needs review flag in the Features UI when you attempt to turn the feature on.  Features will see the existing code and it will not attempt to change it.  Features is designed so that things done through the Admin UI of Drupal are not overriden unless you force Features to do so via a manual review of the feature.

To save yourself a lot of headache later on in the project I would suggest removing the rules before you install the Feature.  Maintain configuration control with Features so that you know if you look at the Features admin page and a feature you have is showing as "overriden" or "needs review" then you have a problem on your website or someone has changed a part of the website.  I personally have a website with about 20 features, all of them never say "overridden" or "needs review" if they do then I know another admin has done something that potentially should not have done.


I would set it up as a single image field with two values and then use https://drupal.org/project/custom_formatters to create a custom formator for that field and do a display hide/show with css or jquery.


you can achieve it with some code in your custom module

function yourmodule_form_alter(&$form, &$form_state, $form_id)
{
    if ($form_id == 'your_form_id' ) { // in your custom content type
    if($form["nid"]["#value"]){  //when we are in edit form
      if(isset($form['field_your_field1']['und'][0]['#default_value']['value']) )
          hide($form['field_your_field1']);
     if(isset($form['field_your_field2']['und'][0]['#default_value']['value']) )
          hide($form['field_your_field2']);
    }
}
}


It may just be your content permissions are not configured.

Go in your admin,  people->permissions->node and look in the "View published Content" permission, make sure anonymous and authenticated user is checked.


Drupal 7 and 8 do not use a straight md5 password hash.  The hash includes a site specific "salt" string that is created with you set up the site.  This is in the settings.php file generally.

To use SQL to set a password, you will need to use the password-hash.sh file which is located in the core/scripts directory.

Run this from your web root directory like ./core/scripts/password-hash.sh` newpassword

Use the string created as the value for your password in query with no Password function.

Re:Drush

You might try running it in the same directory as your site's settings.php file.  With D8, some versions of drush have a hard time finding this unless you run it there or set up an alias for the site.

Older version could find it settings.php based on your location (e.g. in a subdirectory of the site directory or would use the sites/default).  But newer Drush versions need more information.


Purpose of the .htaccess files in the Drupal files directory?

The first .htaccess file in the root directory is for routing and to override any PHP related settings.

The second .htaccess file under sites/default/files is for security purpose, to avoid any file injection. This folder is Drupal's main upload folder.

The upload folder can be moved in different places, or in a multi site setup you could have more than one folder. That is why they provided a separate .htaccess instead of putting everything in one place.


How can I submit a form into a node and save it in the database?

Your FormulaireForm is made by webform? Under this case, you can use rules to create node automatically.


How to retrieve a file via REST from the services module?

I managed to get this working in the end.  I used the poster plugin to request the url and received a message saying that the file doesn't exist.  I'd been using the wrong file ids!  I had looked at the wrong drupal database to choose the file ids.


How to check if custom variation field is null in twig?

just vardump() the product.variation_field_mycustomfield that have an empty field then :
then if it is an array  :

{% if product.variation_field_mycustomfield|length == 0 %}

My custom field: {{ product.variation_field_mycustomfield }}

{% endif %}

otherwise, if it is not an array and it is no empty but it has
default value that is considered as empty:

{% if product.variation_field_mycustomfield == 'the vardump output you get at step1' %}

My custom field: {{ product.variation_field_mycustomfield }}

{% endif %}


Content exists in Drupal but unseen in PHPMYadmin?

First of all allow me to say that you should not delete from db directly unless you are really aware of drupal's architecture and how the db tables are organized. (basically have in mind drupal store information for an entity in multiple tables not only one.)

Secondly have in mind in case you are looking through node table for a node created prior 2013-01-01 m the actual date is saved as unix timestamp (1357020000)

Thirdly allow me to recommend you VBO (View Bulk Operation) module for the exact scenario you are looking for , it will let you bulk delete, unpublish, publish (even has an API for custom bulk operations). I would create a simple view accesible for admins only, exposed filters for node creation date and some basic bulk operation. Please consider using this


Webform responses are NOT content! Responses from the webform module cannot be placed into pages on your site; only administrator users can see results (or specific user roles). You can put answers into Views. (Maybe now that is possible.)

What you want to consider is either webform_entity or the EntityForms module. When to use 1 of these modules is talked about on this docs page. These 2 modules make responses into entity content you can place as content on your site.

Also, webform_entity or entity_forms responses are NOT Drupal nodes; they are custom entities. You cannot moderate their content with say the Workbench module. Good luck auditing submissions before they are made live on your site.


Using Rules to create an Entity Reference if two fields in different entities match?

I don't think I would start with Rules, especially from a performance standpoint. I would first try something like this:

in the Student content type, create an Entity Reference field for the reference, making sure it has a default value, say 0 for ease of access later
Using Field Permissions, hide that field to everyone but admin

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

create a custom module
using hook_node_validate(), check the list of Classes for the existence of the correct code
using hook_node_presave(), update the hidden reference field once it is validated

Now you have something that allows the Student to enter a value, have it validated, and then copy that value into a proper reference field for later use

EDIT

I was curious if I was correct in my initial answer, so I figured it out to check, and it worked - for this example:

Create a content type Class, using the title field as the Class Code
Create a content type Student
Add field to Student content type: field_student_class_code, entity reference to Class content type
use Field Permissions to hide field_student_class_code to everyone but Admin
Add field to Student content type: field_student_visible_class_code, text field
Create a new module called custom_node_reference, and include this code:

function custom_node_reference_node_validate($node, $form, &$form_state)
{
  if($node->type == 'student')
  {
    $lang = $form['field_student_visible_class_code']['#language'];
    $class_value = check_plain($form['field_student_visible_class_code'][$lang][0]['value']['#value']);

    $result = db_select('node', 'table_alias')
        ->condition('type', 'class', '=')
        ->condition('title', $class_value, '=')
        ->fields('table_alias')
        ->execute();

    if($result->rowCount() <= 0)
    {
      form_set_error('field_student_visible_class_code', 'That class code does not exist, please re-enter a valid class code');
    }
  }
}

function custom_node_reference_node_presave($node)
{
  if($node->type == 'student')
  {
    $lang = $node->language;

    // get entity_id for current class code
    $val = db_select('node', 'n')
      ->fields('n', array('nid'))
      ->condition('type', 'class', '=')
      ->condition('title', $node->field_student_visible_class_code[$lang][0]['value'], '=')
      ->execute()
      ->fetchField();

      $node->field_student_class_code[$lang][0]['target_id'] = $val;
    }
  }

If you change the machine names of the fields, you will need to adjust the code to suit


How can I fix a call to undefined function libraries_load() in GeShi Filter?

It appears you tried to use the recommended branch of Libraries API (marked green): 7.x-1.0. Generally, this is a good thing to do, but it can cause problems when modules have dependencies that are still in development.

In this case, Libraries API 7.x-1.0 doesn't the define the libraries_load() function that GeSHi Filter needs. You need to use the latest 7.x-2.x development snapshot.


How to to redirect a form to a certain node for anonymous users?

In buildForm() you can return a redirect response the same way as in a controller:

  public function buildForm(array $form, FormStateInterface $form_state) {
    if ($this->currentUser()->isAnonymous()) {
      return $this->redirect('entity.node.canonical', ['node' => 2]);
    }

    // build $form for authenticated users

    return $form;
  }

Use $form_state->setRedirect() if you want to redirect in a form submit handler.

Using buildForm() as controller by specifying _form instead of _controller is documented and widely used (not in FormInterface, but on DO: https://www.drupal.org/docs/8/api/routing-system). It's unlikely core will ask devs to replace it by their own controller.


Your theme could be breaking the grid. Grid's are usually tables, so they generally work regardless of the theme - but if your theme is making any modifications to it the grid may break. I would suggest examining the HTML code that is being generated for the grid (in Chrome: right click the grid and select Inspect Element). Make sure that it's a table... and also examine the styles applied to it to see if any of them are breaking the normal grid display.
No - you can't tell Views to put certain fields in the grid and certain fields outside of it. I can't really imagine how that would work, or what you mean by that exactly, so it's hard to suggest an alternative. Perhaps two separate Views?


How to apply Panels layouts for CiviCRM pages

Most CiviCRM forms can be accessed with the Webform CiviCRM Integration module: https://www.drupal.org/project/webform_civicrm

Though the integration currently only handles on-site payment methods for contribution forms.

You can build a webform using fields from the CiviCRM form and then use panels to arrange the page, or use Webform Layout module (https://www.drupal.org/project/webform_layout) to arrange the form elements


Check if a field value is already in the database

You should use hook_node_validate
This allows you to return error on the specific field that fails.
e.g.

if($query->rowCount() > 0) {
  form_set_error('machine_name', t('There already exists another node with same machine name - machine name has to be unique.'));
  // where machine_name is the field in this example
}

You wanna check database if value exists.
Can you elaborate exactly what you wanna check? Is it to ensure a specific field only contains unique values?


For content, what are the differences between nodes and terms

Nodes are content. Terms are for categorization of content, they are not content themselves.

Terms are part of taxonomies. Taxonomy is the science of classification.

The relation between nodes and taxonomy terms is that you attach taxonomy terms to nodes, to categorize the node. So if you have a blog node, you may have topics or tags, that would be attached to the blog node. You can use that to find all blogs of a certain category, or tagged with a given term. You can think of hashtags on common SNS sites as being like taxonomy terms. When you click on the hashtag, you can see all posts with that hashtag. The hashtag essentially categorizes the post.

You have listed some ways in which nodes and terms share technical implementations, such as having revisions. But how they are used is entirely different.


How to change a node's term reference value, dependant on date

Take a look at the Computed Field Module, I'm not sure if can handle the date field type or not. on the other hand if Computed Field didn't do what you want you could do a hook_form_alter hook in your custom module. and code your logic there.


Using jquery mmenu, how to close one submenu when I open another submenu?

The easiest method I can think of is to use JS or jQuery to trap the click for every sub-menu item then, onclick, cache a reference to the clicked item, then programmatically close all of the open sub-menus with a loop, skipping the clicked item.

Try something like this:

(function ($, undefined) {

  // Execute once the DOM is loaded.
  $(document).ready(function () {
    // List of expandable sub-menu items.
    var subs = $('.mm-subopen');

    // Iterate through each sub-menu item...
    $(subs).each(function () {

      // Set up onclick handler...
      $(this).click(function () {

        // Cache reference to clicked item.
        var clicked = this;

        // Iterate through list of sub-menu items...
        for(i=0,c=subs.length;i<c;i++) {

          // If current item is not the clicked item...
          if (subs[i] !== clicked) {

            // Get reference to parent <li>, then remove the mm-opened class.
            var parent = $(subs[i]).closest('li');
            $(parent).removeClass('mm-opened');
          }
        }
      });
    });
  });
})(jQuery);

You might need to modify for nested sub-menus, but I hope this helps!


Refer to the Changing PHP memory limits document, you can use

ini_set('memory_limit', '64M');

which should be in your settings.php file.


You need to go to your drupal installation root folder and type the following

chown -R user:www-data .
find . -type d -exec chmod u=rwx,g=rx,o= {} \;
find . -type f -exec chmod u=rw,g=r,o= {} \;

where www-data type the user under which apache/http process runs

Then go at sites/ directory and type the following

find . -type d -name files -exec chmod ug=rwx,o= '{}' \;
find . -name files -type d -exec find '{}' -type f \; | while read FILE; do chmod ug=rw,o= "$FILE"; done
find . -name files -type d -exec find '{}' -type d \; | while read DIR; do chmod ug=rwx,o= "$DIR"; done

See http://drupal.org/node/244924 for more information.


A $block_zebra variable is defined within the block templates to allow for the ability to zebra stripe them in a region.

See hook_preprocess_block() for more info.


Easy date selector for Views Exposed Date Filter

A filters set as "Grouped filters" (as opposed to "Single filter", under "Filter type to expose"), lets you provide a predefined list of options.

With Grouped filters, you can setup your fixed list with date filters that are "offset from the current time". For example:

I'm not sure how you'd accomplish the Custom Range. Perhaps something like the Select (or other) module, or a second filter date filter?


If it's just adding the commas to an array, PHP has implode().

implode(', ', $fields).

I think iRex is asking how to get the values. In this case, I would use the following code.

$fields = array();
foreach ($node->field_name['und'] as $field) {
  $fields[] = $field['value'];
}


Get users by display name on reference autocomplete field

A potentially cleaner/easier way to do that would be to leverage the JSON API.  After you install that module, you should able to make a call to the /jsonapi/user/user endpoint (see the "GET user accounts section on https://www.drupal.org/docs/8/modules/json-api/fetching-resources-get), and parse out the UIDs into the array.


This isn't really a Drupal question. Go to https://mail.google.com/mail/#settings/general and look at the Conversation View. This sets whether emails of the same topic are grouped together. So they aren't grouped together based on the from: address but on the title. Just set it to Conversation view off and save the settings.

Alternatively, make the subject of the mail unique. For example by adding the name or email address to it, or a unique key.


How do I resolve a merge conflict with features?

Check the panes with the following uuid "bf806592-c85c-4155-a97c-516f72427e4e"
and "992af322-74c5-4a5c-a261-1e73677d3645".
Check which one should not be there and remove it from the code.


Pass view contextual filter arguments programmatically

I got the solution. It can be done using hook_views_pre_view(). Since hook_views_pre_view() allows altering a view at the very beginning of views processing, before anything is done, I am able to feed the arguments to the view.

function MODULE_NAME_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == 'myview' && $display_id == 'page_1') {
    $tids = custom_function();
    $args[] = implode('+', $tids);
  }
}

Hope this is useful to someone :)


Overriding the Blog username breadcrumb in the native Blog module

A node preprocess function in your template.php file would probably do the trick:

function MYTHEME_preprocess_node(&$vars) {
  if ($vars['node']->type == 'blog' && $vars['view_mode'] == 'full') {
    $bc = function_to_get_breadcrumb();
    drupal_set_breadcrumb($bc);
  }
}

This should happen early on enough in the page build process for the changes to make their way through to page.tpl.php. You could also look at doing this in hook_node_view() in a custom module if you'd prefer.


Prevent Field From Updating On Follow Up Saves?

You can write a small custom module to lock down the original value of the field on edit, probably using hook_form_FORM_ID_alter would be the clearest way.

Difference between create new and edit node in form alter provides a decent example, try that. Basically, you have to check in the $form object for an existing node. If it's an edit form, you have a node id already; if it's a new node, you don't.


You need to load the related field storage config entity and change the locked status:

\Drupal::entityTypeManager()
  ->getStorage('field_storage_config')
  ->load('node.field_foo')
  ->setLocked(FALSE)
  ->save();

This is just an example - you should inject the entity type manager instead of calling the global version if contexts allows.


You may be interested in the Panels module.  You can create custom layouts, include views/custom content, and more.

From the project page:

  An Overview of Panels
  The Panels module allows a site administrator to
  create customized layouts for multiple uses. At its core it is a drag
  and drop content manager that lets you visually design a layout and
  place content within that layout. Integration with other systems
  allows you to create nodes that use this, landing pages that use this,
  and even override system pages such as taxonomy and the node page so
  that you can customize the layout of your site with very fine grained
  permissions.


user_presave doesn't work correctly when new account is created

As stated in the documentation (https://api.drupal.org/api/drupal/modules%21user%21user.api.php/function/hook_user_presave/7), you need to check whether the user is being created or not with the following code:

if ($account->is_new)

The reason is that $edit contains the values submitted, and $account contains the existing user data - but on user registration, there is no user that already exists in the database.
Your code should check whether new user is being created and in that case assign some default value (like you already have with $B= taxonomy_term_load($tid);)


The problem is not drupal_goto() but your usage of it in a node. THere is a long standing issue in Drupal core to deal with this but I honestly think doing this is just wrong.

Instead of putting it in a node, you should create a custom module and put it in a page callback. See What are the downsides of using 'custom' PHP code in blocks, nodes, views-args, etc? why it's a bad idea in general to use PHP in nodes, blocks and so on. You've seen one of those yourself, namely that it can be extremely hard to find out where the problematic code is actually coming from.

That said, the last comment in the linked issue points to a Field redirection module that is however currently limited to user/node references and links. And it's not dynamic as your code is. But again, for something like that you really should be creating a custom module.


Is there a way to remove a menu item from the active trail without removing it from the menu parent?

This is a common headache. I keep meaning to write a contrib module to address this by letting users define a "canonical" menu item in the event there are several menu items that point to the same page in the same menu.

That said, there are some workarounds you can use.

The best option is to use the Redirect module. You create a redirect to your Donate and Volunteer pages then put the redirects in the menus.

So if your volunteer page is at /volunteer and donate is at /donate, then you can create two redirects. One called /go-volunteer and another called /go-donate which redirect to their respective pages. Then you'd put /go-volunteer and /go-donate in the menu which, when clicked, will take the user to the appropriate page.

Since they're redirects, they won't trigger the active trail.


How often does drupal core need updating?

There is no "rule" but update as soon as it's released.

Usually Drupal core updates (bug fixes) are released once in a month but in case of a security vulnerability, there will be an immediate release.

I usually leave Update Status module enabled and configured to check for new releases every week.

Read more about Drupal core release cycle here. (This is about major Drupal releases, eg. 6, 7 and upcoming 8)


How to display eck edit form in ctools modal or in other page?

The right way to load the edit form of a custom entity bundle created with ECK is by using the eck__entity__edit function provided by the ECK module.

Usage example:

$output = eck__entity__edit($entity_type_name, $entity_bundle_name, $entity_id);


Use this in your theme so menu items can be processed as html

use Drupal\Core\Render\Markup;

/**
 * Implements hook_preprocess_HOOK()
 * processes 1 nested level of menu items
 */
function THEMENAME_preprocess_menu(&$vars){
  if($vars['menu_name'] == "main"){
    foreach($vars['items'] as &$link){
      $link['title'] = Markup::create($link['title']);
      foreach($link['below'] as &$nestedlink){
        $nestedlink['title'] = Markup::create($nestedlink['title']);
      }
    }
  }
}

Alternatively you can use css to make regular white space not wrap

.menu li a {
    white-space: nowrap;
}

Of course you have to adjust css for your particular menu class


How can I setup Git/Drush dl/make caching of Drupal projects?

There is a blog post about locally cached git repositories here: http://randyfay.com/node/93


Admin page to show 2 blocks (or page+block) with 1 filter that affects both blocks

The described scenario doesn't need custom coding as it is shipped with Drupal 7 Views module.

The approach to use a views block in a views page that shares the same filter can be done using the "Attachment" view.

You can find more about views attachment here

Also, there is an answer to place the attachment in a different page region here

Hope this answers your question.


Not able to alter field value/s using hook_views_pre_render or views api hook functions

This is not a specific answer for your situation but I would like to advise you a better way of managing it.

Instead of rendering the views using Fields you can render each row by rendering as Content where you can choose a dedicated View mode which can be easily overridden using the standard template_preprocess_node.

This will bring a lot more flexibility in your Web application.


Filter articles by tag equal to the node title

I'm trying to create view which will show all Articles which tag is
  equal to title of currently being viewed node (which content type is
  not Article).

Instead of being equal to title, you can approach it like this.

Go to your Author content type, and in Manage fields, add a taxonomy term reference field. Select Tags.

Edit your Author Content Type and give it the same tag as the title.

In other words, you tag the Chuck Norris node with the Chuck Norris tag, which means now your Chuck Norris node as a term ID.

Then in your view


How do I track a publicly downloaded file?

hook_file_download doesn't run for public file downloads.

Control access to private file downloads and specify HTTP headers.

If you want to track public file downloads, you will need a different approach.
For example, track downloads with Google Analytics event tracking


How to add links in the title for a profile text field

It sounds like you should be looking at the Terms of Use module, which will place the check box on the user registration page. It provides a link to a node, which you create, outlining the terms the user must agree to to register on the site.

On the project page they also mention the Legal module, which provides similar, but more extensive options.

Check both, and see which best satisfies your needs.


Creating a temporary content type on the fly?

$node_type = array(
  'type' => 'temporary_node_type', // This is the machine name.
  'name' => t('Temporary Node'), // This is the human name.
  'base' => 'node_content', // If you set this to your module name, then
                            // *your module's* hook_insert(), hook_delete(),
                            // etc. will get called in addition to
                            // hook_node_*()
  'description' => t('Description.')
  // A full list of options is at http://api.drupal.org/hook_node_info.
);

$node_type = node_type_set_defaults($node_type);

node_type_save($node_type);

// Do something with your node type. You can also add fields here if you
// would like.

node_type_delete($node_type);

Note 1: People with the "administrator" role will see this type on node/add every once and a while, depending on how often you do this.

Note 2: You want to use something more then a hard-coded string for your type attribute to avoid collisions.


The current-user token will always take its data from the current user, you can't override it with parameters. See user_tokens:
if ($type == 'current-user') {
  $account = User::load(\Drupal::currentUser()
    ->id());
  $bubbleable_metadata
    ->addCacheContexts([
    'user',
  ]);
  $replacements += $token_service
    ->generate('user', $tokens, array(
    'user' => $account,
  ), $options, $bubbleable_metadata);
}

If you need to control the account object used for the token, use user instead
$message = 'Hey, [user:account-name]';
$message_value = $token->replace($message, ['user' => $account]);


How to use feeds module to import multi-value fields?

Feeds and Feeds Tamper worked for me too. To get one row for each multi-value field I used the GROUP_CONCAT() function from MySQL. I used this in conjunction with the Feeds_SQL module.


The EU Cookie Compliance module doesn't display the message

I have tried it in d6 and d7 and had similar problems in bringing it up for the first time, it showed after enabling the module, setting the permissions to anonymous user, logging out and deleting all cookies from my domain, alternatively using an anonymous browser window. So it might be that you have the cookie already.


Is it possible for a site owner's user account to **ever** have a permissions issue?

User #1 only bypasses user_access(); if something runs its own access calls, and doesn't call user_accces(), that user won't get any special handling.


How to correctly modify Taxonomy Term selection Plugin

The annotation in the sample code of my question was wrong. With the help of the first comment to this issue I was able to solve the problem (see accepted answer there). Although this question is a bit different it might be marked as duplicate to How to display more than 10 items in link widget autocomplete?.

Anyway I want to leave the custom plugin including the annotation:

<?php

namespace Drupal\custom\Plugin\EntityReferenceSelection;

use Drupal\Component\Utility\Html;
use Drupal\taxonomy\Entity\Vocabulary;
use Drupal\taxonomy\Plugin\EntityReferenceSelection\TermSelection;

/**
 * Provides specific access control for the taxonomy_term entity type.
 *
 * @EntityReferenceSelection(
 *   id = "custom:taxonomy_term",
 *   label = @Translation("Custom Taxonomy Term selection"),
 *   base_plugin_label = @Translation("Custom Taxonomy Term selection"),
 *   entity_types = {"taxonomy_term"},
 *   group = "custom",
 *   weight = 2
 * )
 */
class CustomTermSelection extends TermSelection {

  /**
   * {@inheritdoc}
   */
  public function getReferenceableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) {
    if ($match || $limit) {
      return parent::getReferenceableEntities($match, $match_operator, $limit);
    }

    $options = [];

    $bundles = $this->entityManager->getBundleInfo('taxonomy_term');
    $bundle_names = $this->getConfiguration()['target_bundles'] ?: array_keys($bundles);

    foreach ($bundle_names as $bundle) {
      if ($vocabulary = Vocabulary::load($bundle)) {
        if ($terms = $this->entityManager->getStorage('taxonomy_term')->loadTree($vocabulary->id(), 0, NULL, TRUE)) {
          foreach ($terms as $term) {
            $options[$vocabulary->id()][$term->id()] = Html::escape($this->entityManager->getTranslationFromContext($term)->label());
          }
        }
      }
    }

    return $options;
  }

}

One thing I want to point out, which was not part of the above linked answer is the base_plugin_label = @Translation("Custom Taxonomy Term selection") (solution found on d.o. issue). Without that I got the following notice:

  Notice: Undefined index: base_plugin_label in Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem->fieldSettingsForm() (line 336 of core/lib/Drupal/Core/Field/Plugin/Field/FieldType/EntityReferenceItem.php).


How do I programmatically attach a file to a file field in a node?

In your custom form use code like this:

$form['imagefile'] = [
      '#type' => 'managed_file',
      '#title' => $this->t('Imagefile'),
      '#default_value' => $this->configuration['imagefile'],
      '#weight' => '0',
      '#upload_location' => 'public://images/redaktion/',
    ];

And here's a piece of code how it works low level:

// check if the folder exists
$folder = date('Y-m', time());
$data = file_get_contents($imagefilepath);
if (!is_dir("/home/rainer/src/asdent/web/sites/default/files/images/pics/{$folder}")) {
      mkdir("/home/rainer/src/asdent/web/sites/default/files/images/pics/{$folder}");
}
// create the file entity
$photo = file_save_data($data, "public://images/pics/{$folder}/".$filename, FILE_EXISTS_REPLACE);

// later in your entity::create:
'myimage' => ['target_id' => $photo->id()],

The trick is to create the file entity beforehand and then link the custom entity to it.


textfield with #disabled = true, #input = false

Use a markup element instead.

$form['element'] = array(
    '#type' => 'markup',
    '#markup' => 'This is the thing you want people to see. You can use html, too.',
);

You don't actually have to specify #type => 'markup' because drupal defaults to that type if you don't specify, but I do anyway as it seems to be good practice.


Change contact form to email based on selection?

There isn't a way to make behave like its D7 incarnation without some custom code. You might, however, find this issue on d.o. useful; it contains a patch that adds a customizable block which lets you select a contact form (and thus recipient) to use.


How to display photo properties (ISO, Aperture, Exposure, Shutter Speed) in Drupal 7

The exif module should get you going.

  The Exif module allows you to display Exif metadata on image nodes.
  Exif is a specification for the image file format used by digital
  cameras.


Display number of pending messages and friend request on the user menu

This will return the unread private messages in Drupal 7.

<?php
global $user; privatemsg_unread_count($user);
?>

Refer this for more discussion

This will return pending relationship request for the loggedin user.

<?php
function _count_pending_relationships($account = NULL) {
  $counts = &drupal_static(__FUNCTION__, array());
  if (!$account || $account->uid == 0) {
    global $user;
    $account = $user;
  }

  if (!isset($counts[$account->uid])) {
    $count = 0;
    $pending_relationships = user_relationships_load(array('requestee_id' => $account->uid, 'approved' => 0), array('count' => TRUE));
    if (!empty($pending_relationships)) {
      foreach($pending_relationships as $requester_uid => $relationship) {
        if($account->uid != $requester_uid) {
          $count++;
        }
      }
    }
    $counts[$account->uid] = $count;
  }

  return $counts[$account->uid];
}
?>

Refer this for detail discussion.

You can create a block and create respective links with the functions shown above.


Add Commerce Checkout progress bar and extra stage

You want the Commerce Checkout Progress module.


Add css file to the Admin Theme of the Commerce Kickstart distribution?

I would strongly suggest to create a subtheme for additional CSS. That's what subthemes are for, after all, and it's less work than to make a module. Simply use info file and it's stylesheets[all][] entry.

If you have time, you can investigate how AdaptiveTheme allows GUI editing of CSS, and implement this in your custom theme. AT is open-source after all, so it would be legal to copy-paste this functionality. It will make your life easier for future:


If you define the modules in the subdirectory as dependencies of your main module, then they'll be enabled once your "controller" module is.

i.e.

name = Really Neat Widget
description = Provides a really neat widget for your site's sidebar.
core = 7.x
package = Views
dependencies[] = MODULE_ONE
dependencies[] = MODULE_TWO

Source

Alternatively, you could take a look at the Master module.


Create a view of all nodes that have the same value for a specified field as the current node

Use Page manager and panels and add the view as a content pane. Then, pass the node's field's value as an argument to the pane(s) on the panel and you should be good to go.


It can be done by wrapping your table in a form, and then use the form API to render your table and re-render it on submit. You can have a look at this comment: https://www.drupal.org/node/1770512#comment-6428358

In short the render funtion:

function MY_MODULE_build_form($form, &$form_state) {
  // Filter field.
  $form['title'] = array(
    '#type' => 'textfield',
    '#title' => t('Title to look for'),
    '#size' => 15,
    '#default_value' => isset($form_state['storage']['title']) ? $form_state['storage']['title'] : '',
  );

  // Submit button.
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t("Find"),
  );

  // Modify table array here.
  // If your API supports filters, you can use that too.
  // My regex is bad, so you might need to tweak this.
  if (isset($form_state['storage']['title'])) {
    $temp_rows = array();

    foreach ($rows as $key => $row) {
      if (preg_match("/" . $form_state['storage']['title'] . "/", $row['field_to_search'])) {
        $temp_rows[$key] = $row;
      }
    }

    $rows = $temp_rows;
  }

  // Render the table array.
  $form['table'] = array(
    '#theme' => 'table',
    '#header' => $header,
    '#rows' => $rows,
    '#empty' => t('Empty Rows')
  );

  return $form;
}

And the Submit function

function MY_MODULE_build_form_submit($form, &$form_state) {
  // Set the provided filter value in the storage.
  $form_state['storage']['title'] = $form_state['values']['title'];
  // Show the form again.
  $form_state['rebuild'] = TRUE;
}

You might want to fancy it up with some fieldsets, but those are left out to keep the answer understandable.


Avoid duplicates on a view based on results from another view

In the contextual filters, there's an option called «Allow multiple values» just above «Exclude». That option lets you return multiple values separated by commas (and) or mores (or).

So, I just use this code in the «Provide default value» field:

$my_view_name = 'videos';
$my_display_name = 'otros_importantes';

$my_view = views_get_view_result($my_view_name, $my_display_name);
if ( $my_view!=null ) {
  foreach($my_view as $view_row){
    $nodos[]=$view_row->nid;
  }
}

if(isset($nodos)){
  return implode(",",$nodos);
}
else{
  return 0;
}

And that's all, the nodes shown on that display are ignored.


You can use drupal_mail() function to send the mail data. You can also use HTML Mail module to integrate nice email templates.

I have shown drupal_mail() function.

$params = array('current_conditions' => $data);
  $to = 'user@example.com';
  $message = drupal_mail('example', 'notice', $to, $language, $params, FALSE);
  // Only add to the spool if sending was not canceled.
  if ($message['send']) {
    example_spool_message($message);
  }


How to configure EU cookie compliance module for only Google Analytics

In the permission page (admin/people/permissions), check "Display EU Cookie Compliance popup" for the anonymous user.


Why does the selected payment method comparison always fail?

Part 1 - Getting your rule to work

Try to add a Rules Condition Entity has field to make the appropriate field available for further processing in your Rules. That's also what is mentioned in the Rules UI when you're adding a "data comparison" condition: somewhere it says:

  The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type').

Don't believe me (yet) about my recommendation here ... first add an extra Rules Action as your very first Rules Action, to simply display the actual value of that field you try to use within the "If" of your Conditional Rules construct ... Without such "entity has field" Rules Condition, I bet the value of that field will be shown as empty (or blank). Which would then also explain why your "If" always results in a FALSE ...

For a video tutorial that illustrates the importance of this Entity has field condition, refer to Data types and data selection, especially what is shown between about 13:30 and 17:30 in that video.

Note: it's hard to tell from the current content of your question what the exact field (for which to add such Rules Condition) should be in your case. But my best guess is some field about the payment method (possibly method_id?)

Part 2 - Simplify your rule

From the current content of your rule, it seems that you want to perform a Rules Loop as a Rules Action, but only if some condition (the "If" you added using "Conditional Rules" module) is true. And then as the very last Rules Action the rule shows that test pos event message.

If this very last message is just for debugging (i.e if it is not really needed after you get it to work anymore), then it seems to me that you could replace that "If" (added using Conditional Rules) by a regular Rules Condition. And by doing so your rule would not require the Conditional Rules module anymore.

Plan B

As per the comment posted below this answer, you may want to try a completely different approach ... which is based on this commit, and related to issue # 1278156:

Use the Rules Condition Selected payment method comparison, located within the Commerce Payment group.
Check if its value is equal to your 'maro_credits'.


I finally found out about language_negotiation_get_switch_links($type,$path). The tricky part is the $type argument. The types are defined by implementations of hook_language_types_info() and at least for my setup $type = 'language' does the trick.


How do I store the input value on form submission?

I would have thought you would be able to do something like this in your form handler...

'#default_value' => $form_state['post']['name'] ? $form_state['post']['name'] : 'some default value',

...but perhaps since this is in a block, it is being called "fresh" each time the page is displayed.

So, quick and dirty (and possibly all hideously wrong) the following does work...

'#default_value' => $_SESSION['foo_bar_baz'] ? $_SESSION['foo_bar_baz'] : 'some default value',

...if you put...

 $_SESSION['foo_bar_baz'] = $form_state['values']['name'];

...in your submit handler.  At least for logged in users anyway, and will persist during his/her session.

Hopefully there is a "drupaler" way of doing this, but in the meantime, flame retardant suit on.


Limit entity reference field formatter to certain entity types

I think this will work...

There is an isApplicable() method in Drupal\Core\Field\FormatterBase. You can implement it in your FieldFormatter class like this:

public static function isApplicable(FieldDefinitionInterface $field_definition) {
  return ($field_definition->getFieldStorageDefinition()->getSetting('target_type') == 'user');
}


ImageCache Actions is the right module which you're looking for. Enable Imagecache Actions and Image Effects Text module

Go and edit the image style at admin/config/media/image-styles and select effect Text.


Did you look at Debugging your Email on a development server? Have you looked at the Rules module and the Auction Rules to see if their firing (it sounds like they are)? Did you create hook_mail_alter() to see what email drupal thinks it's sending?

Does your "Create Account" email message fully validate as an email sent from a valid domain, etc.

It's email -- there are no easy answers :)


Jquery Library Conflict Error in Drupal 7

I would wager a guess it's because (or related to) Drupal including it's own version (1.4) of jquery, and you trying to include a second copy at version 1.11.2 - some functionality is deprecated in later versions of jquery, items that drupal and its modules are expecting to find. If you need to increase the version use something like the module Jquery Update instead of your own add_js and see if that solves it.

Upgrades the version of jQuery in Drupal core to a newer version of
jQuery.
Updates...
Drupal 5 to jQuery 1.2.6
Drupal 6 to jQuery 1.3.2
Drupal 7 to jQuery 1.5.x, 1.7.x, 1.8.x, 1.9.x, 1.10.x and jQuery UI 1.10.2
Drupal 8: TBD


What does Page Content contain in Panels Everywhere when site template is enabled?

A page panel will be placed where the main page content is located.  The page panel will be displayed only when the conditions of its Selection rules and Contexts are satisfied.  You can define alternatives by creating multiple variants for the panel and modifying the settings to meet your needs.  Panels will search through the variants and go with the first variant that meets the criteria so the order you place the variants in may matter.  Using Panels Everywhere, you would set the overall layout for your site pages in variants to the default site panel.  The various page panels would then be displayed in the regions as defined for them.

You can also create mini-panels and view content panes which act similar to blocks except that, like page panels, you can define selection rules and contexts for them and place them anywhere else on the default panel variants you desire.  So you can provide content related to your main content based upon the context (users, tax terms, field settings etc.) that apply to the main content display.

I'm not sure if I've fully answered your question.  What do you want to achieve in your site setup?


The test-run is outputting XML and reporting success on the generation, which is useful for Jenkins, but not Travis CI.

drush test-run --xml 'Andy Truong'

Change that to

drush test-run 'Andy Truong'

And you should be set.

For reference, see https://drupal.org/project/travis_ci_drupal_module_example and https://travis-ci.org/sonnym/travis-ci-drupal-module-example


problem with printing multiple cck value inside node-type.tpl.php

Your code uses foreach which takes $node->field_authors[0,1,etc] and relays that value through $item.  If you want to know the key for the current field inside your foreach loop, rewrite the code like this:

$dots = '';
$i = 0;
foreach($node->field_authors as $key => $item) {
    $i++;
    if ($i < count($node->field_authors)) { $dots = ',  '; } else { $dots = '.  '; };
    print '<span>'. $node->field_authors[$key]['view'].$dots.'</span>';
    // note: $node->field_authors[$key] is the same as $item['view']
}


Menu does not appear while opening my site

Please login through admin credentials. Check module permissions for Toolbar for authenticated users. Check that if it is unchecked. Try flushing drupal cache.

Once you see the toolbar. You can install admin_menu for better administration menu.

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


Programmatically setting an image field from hook_node_insert (drupal 7)

node_save() actually invokes hook_node_insert() so calling it from inside that hook probably isn't the best idea (I'm surprised you don't get out of memory errors doing that actually).

Instead you might want to use hook_node_presave(), which is called before the node and associated data is committed to the database:

function MYMODULE_node_presave($node) {
  $image = file_get_contents('http://drupal.org/files/druplicon.large_.png');
  $file  = file_save_data($image, 'public://drupalicon.png',FILE_EXISTS_REPLACE);
  $node->field_screenshot[LANGUAGE_NONE]['0']['fid'] = $file->fid;
}

That way you won't have to call node_save() so you won't get the error, and the field data will save with the node as normal.

As hook_node_presave() is called for both inserts and updates, you might want to add a condition in there to check whether the node is new or not (checking $node->nid will probably suffice). Otherwise you'll end up doing this operation every time the new node is subsequently saved.


Commerce add to cart form fails when loaded via Ajax

This is an old issue, but it was never answered and ranks high on google. The solution is to rebuild the submit button via javascript after the view has loaded:

$(".view").ajaxComplete(function(event, XMLHttpRequest, ajaxOptions){
          response = XMLHttpRequest.responseText;
          result = response.search(/"status": false/i);
          if(result == -1){
            $("form.commerce-add-to-cart").each(function(){
              $(this).attr("action",window.location.pathname);
            });
          }
          else{
            //console.log("failure binding on ajax complete");
          }
        });

Solution taken from here: https://www.drupal.org/node/1294164#comment-5343066


How do I add reCaptcha to a form programmatically?

Use the following (after installing the reCaptcha module):

$form['captcha'] = array(
  '#type' => 'captcha',
  '#captcha_type' => 'recaptcha/reCAPTCHA',
);


How to use an aliased content title for a Views contextual filter?

How I attacked the spaces/punctuation issue ( http://drupal.org/node/786612 ) in Drupal 6 was by creating a url_safe_title text field and putting it in any content type that needed to be looked at, searched for, etc by it, and then having nodeapi() "fill it in for me" like this:

function MODULE_nodeapi(&$node, $op, $teaser = NULL, $page = NULL) {
  if (isset($node->field_url_safe_title) && $op == 'presave') {
      module_load_include('inc', 'pathauto');
      $node->field_url_safe_title[0]['value']=pathauto_cleanstring($node->title);
  }
}

You can get fancy and hide the field with permissions, css etc so your users don't see it when creating content. I use http://drupal.org/project/nodeformcols to hide it and hide it from $content on display, too.

So, what this does is change simple titles like Hello World into hello-world but also online-led reporting into online-led-reporting with the added/needed benefit of being able to get back to "online-led reporting" from it.  It also helped out with stuff like Kukla, Fran and Ollie that turned into kulka-fran-ollie :)

So now in Views I use this field instead of the node title when I needed to grab things.  Just have to be aware of uniqueness, but that's another story in of itself :)


Views can render both question and answer. Beyond that you need jQuery and CSS for the hide/show/flip effects.


What is the best way to write a cron that deletes a very large number old nodes and comments?

I would never think running raw SQL queries is a good idea because that can mess up a lot of things such as site maps, search index, caches, etc.

it's just a node_delete() and shouldn't be much slower that deleting a bunch of rows in multiple tables.

Whatever that is, you will need to implement hook_cron and retrive nodes to be deleted from 'node' table.

If you run a node_delete you won't need to delete comments.

You can limit the number of nodes to delete in a single cron run using LIMIT  keyword.

Update:
You might want to have a look at Delete All module. and there is a patch (which I submitted) to use the Batch API to do the job. From my experience I know even the Batch API can't handle it (or you have to wait several days with the browser open).

You can just use hook_cron to load a bunch of nodes to be deleted, and then delete them in your preferred way (node_delete or raw SQL). Let the cron finish, and in the next run, it will grab some other nodes.
Just get your nodes from node table and limit it with a LIMIT.


It was from the custom relation i made to the Administration: Nodes (Content),
now it works after removing the unneeded relations.


It should be something as simple as

$account = user_load($GLOBALS['user']->uid);
$edit['field_keys_available'][LANGUAGE_NONE][0]['value'] = 'new value';
user_save($account, $edit);

The comments in the user_save() docs have some more details and examples.


Use the following code,

$value = $node->field_test[$node->language][0]['value']

This to get the value for the text field alone for other fields format will chage.


I think the simplest solution would be:

<div id="content-area" class="span<?php echo $page['sidebar_first'] ? '4' : '8'; ?>">


How do I access a node object property, if it is an array?

There's no real need to convert it to an array, as you can already access members of a FieldItemList as an array:

$first = $node->field_1[0]->value;
$next = $node->field_1[1]->value;

This:

$node->field_1->value;

Is just a shortcut to the first item in the collection anyway (see FieldItemList::__get()).

If you need the values in exactly the format you specified, FieldItemList is also iterable:

foreach ($node->field_1 as $delta => $item) {
  $an_array[$delta] = $item->value;
}


I'm not sure why you'd need to get it from the $page variable, you can get the query string from the $_SERVER superglobal at any point in the page execution, and convert it into an array with PHP's parse_str():

function MYMODULE_page_alter(&$page) {
  // Convert the query string to an associative array named $qs
  parse_str($_SERVER['QUERY_STRING'], $qs);

  // For the string name=jeff&foo=bar:
  //
  // $qs['name'] = 'jeff';
  // $qs['foo'] = 'bar';
}


Creating Custom Drupal 7 Registration Form

I have tested the code and it's almost working as it's intended to be. One thing to note is when you placed the template file inside of the templates folder then the following should work.

On the icompany_theme() function, change the path value from 'path' => drupal_get_path('theme','icompany'), to 'path' => drupal_get_path('theme','icompany') . '/templates', which specifies to look for the file inside the templates folder.

Then flush your caches.


How to send an email to the node author when a date is approaching?

Have you tested Rules, this is the module to do such actions based on events.
Here is a tutorial to help you with this: Publish content based on a CCK date field.

Also don't forget to enable the debugging feature of rules under admin/rules/settings.


The best way to do this is to see what your available theme suggestions are for that node.

In your theme add the following snippet and clear cache, refresh page, etc.

function YOURTHEME_preprocess_node(&$vars) {
   var_dump($vars['template_files']);
   //dsm($vars['template_files']); // if devel module installed
}


What is correct selector for radios to determine if ANY radio is selected?

Had same problem today. A slight modification of the negated value expression proposed on this comment: "Empty Radio Selection" on drupal_process_states() API page, did the trick for me!

'#states' => array(
   'visible' => array(
     ':input[name="radios-name"]' => array('!value' => false),
   ),
 ),

I just wanted the select list with the above #states entry to be invisible while no selection has still been made on my list of five radios (sharing name "radios-name").

Radios were also '#required' => true, in my case and all 5 individual radio-buttons have non-numeric string values. No #default_value is specified in my case either.

Disclaimer: I have only tested this on Chrome!


Add content type filter on taxonomy page

Instead of creating the two different content type i.e. online and offline, you should create vocabulary with two terms and then add "term reference" field to that content type.


How do I log in if I can not get the login prompt page to come up as it should?

Drush

  To get one-time login for the specific user, use this syntax:

drush uli <user>

  Where <user> is either uid (e.g. 1), user name, or email address
  for the user.

  Custom code

  You can use user_pass_reset_url() function in your
  custom code.

  Generates a unique URL for a user to login and reset their password.

  Ex:

$uid = 1;
$account = user_load($uid);
$link = user_pass_reset_url($account);

Source: Kenorb's answer to How to get one time login for all the users?


Commerce Kickstart and product variations

TLDR: This is due to how Commerce Kickstart is configured for entering new products. You enter product variations while adding the product.

When you create a product in Commerce Kickstart, you're actually creating the node that the customer will see. Scrolling down the page, you'll see the ability to add the individual product variations (which are the actual product entities) like so:

This is an Inline Entity Form (aka IEF). See, normally when you'd use Drupal Commerce, you'd need to create all of your individual entities and then add them to a product using a product relationship field. But this a Drupal field widget take takes that step out by letting you enter in your product data and relate it to the display node in one step.

If you want to see all of the product variations, there should be a tab at the top of the Products admin page that will take you to a listing:

You can edit products here, but you can't add them directly because of how Kickstart controls the product add process.


Add base element to your sites theme template file:

YOUR_THEME_NAME_preprocess_html(&$variables, $hook) {
    $url = 'default';// default url
    if($application1) {// your condition for app1
      $url = 'app1';
    } elseif($application2) {// your condition for app2
    $url = 'app2';
    }
    $data = array(
      '#tag' => 'base',
      '#attributes' => array(
      'href' => $url,
      ),
    );
    drupal_add_html_head($data, 'base_href');
}

Put it into your template.php

Ref: https://stackoverflow.com/a/35725528/3770000


Unable to add WHERE conditions as OR to query object

Am I adding these conditions to the query object correctly (assuming I want them as OR)?

Not quite; all components of the the OR need to be added to the condition object, so you need to do something like this:

$query = db_select('node')->fields('node', array('nid'));

$db_or = db_or();
$db_or->condition('type', 'type1')
  ->condition('type', 'type2')
  ->condition('type', 'type3');

$query->condition($db_or);

That'll give you this query string:

SELECT  node.nid AS nid
FROM
{node} node
WHERE ( (type = :db_condition_placeholder_0) OR (type = :db_condition_placeholder_1) OR (type = :db_condition_placeholder_2) )

  Is there a way to remove the initial condition so that I could just add my own WHERE condition from scratch?

Yes you can use SelectQuery::where(), but there's really no need. You can use the above, or preferably...

  Is there a better way to do this?

Yes, by using IN as you originally planned:

$query = db_select('node')
  ->fields('node', array('nid'))
  ->condition('type', array('type1', 'type2', 'type3'), 'IN');

That gives:

SELECT  node.nid AS nid
FROM
{node} node
WHERE  (type IN  (:db_condition_placeholder_0, :db_condition_placeholder_1, :db_condition_placeholder_2))

Note that the third parameter of "IN" to condition() isn't strictly necessary, as the DB class automatically assumes "IN" if an array is passed.


drupal commerce rule to skip duplicate sku in cart

You can use unique field , autosku and tokens module

using that module set the name of sku using tokens
While generating sku use tokens

the parameters which u know differentiates 2 products should be used in tokens

Like if quantity and size is the parameter which differentiates your 2 products and defines two products as unique
then
using tokens(for e.g.) [product:qty] and [product:size]
set the sku title
and using unique field set the sku as required and unique field

You can try the following function to edit the quantity :
you can set cart quantity for a single item to be default value 1.
hook_commerce_cart_line_item_refresh($line_item, $order_wrapper)

  Allows modules to perform additional processing to refresh an
  individual line item on a shopping cart order.

  Prior to this hook being invoked, product line items will have already
  had their sell prices refreshed via the creation of a new line item
  for the same product being passed through Rules for calculation.

  Parameters

  $line_item: A line item object that should be updated as necessary for
  the refresh.

  $order_wrapper: An EntityMetadataWrapper for the order the line item
  is attached to.


multisite multilingual over different directory

I was solved this problem . May be use to you for only Multisite

Solution:

Give Symbolic link form mulitsite to site1
Executed that command line
ln -s /var/www/multisite /var/www/site1

Rename example.sites.php to sites.php
// 192.168.1.99 local IP address
$sites['192.168.1.99.site1'] = 'site1';

put this line in sites.php

No need to use RewriteBase /xx

If you have any problem in symbolic link use this link https://superuser.com/questions/68685/chown-is-not-changing-symbolic-link

and also How do I setup multiple sites with one database in Drupal 7 (or) Multisite Apache configuration with Drupal


Problems Installing Colorbox Module "Requires: Libraries (2.x) (incompatible with version )"

It should just happen when the Libraries API doesn't contains the version line in libraries.info. That would explain why the message doesn't report the Library API version.

I made a test on my test site. On the .info file for a custom module I added the following line.

dependencies[] = libraries (2.x)

In the libraries.info file, I removed the following line.

version = "7.x-2.0+5-dev"

When I visited the module page, I saw the following message for my custom module:

  Requires: Libraries (2.x) (incompatible with version )

I thought it would happen when the installed module was a development snapshot, but it's not true. If I add the line I removed, all back to normality, even if I installed the development snapshot of the Libraries API module.

If you copied the Libraries API files from a Git repository, the libraries.info file is missing the version line, and that would explain the message error you see.

Removing the version from the dependency line is fine, as long as you don't install the Libraries API module 1.x by mistake.


Average value of Multiaxis FiveStar value

The easiest thing to do would be to set the value yourself with either hook_entity_insert/update or in a custom submit handler to the form.

The values are stored in the fields tables and not voting API when you use the five star with fields.


getting Drush to cooperate with Mercurial

wow ... drush up to my knowledge shouldnt touch any (dot) hidden files or directories. Drush up just looks for more recent module packages and updates them, which has nothing todo with .hg or .svn or .git directories.

Are you talking about a global .hg directory for your projects, or like an .hg directory within a module folder somewhere!?


You will find some documentation in the README.txt that comes with the module.

To use the module, you first need to get drupal commerce up and running. Then your products will be available for sale via the POS, once installed.

Also look at the commerce pos issues queue as v2 still has some issues being resolved.

I have used 7.x-1.x-dev extensively, and you can access the POS via: admin/commerce/pos

The configuration is via: admin/commerce/pos/config

If you have any specific question, please amend your original question.

Edit:

Make sure you are using the latest 7.x-2.x-dev version to get latest fixes.
Also see this issue relating to products not showing: By default, no products are available in the POS
POS is available via: admin/commerce/pos


Changing menu paths for existing nodes in Drupal 7

Take a look at the Pathauto module. You can configure it to create paths automatically with a given pattern for individual content types. It also has options to bulk delete and update existing paths.


How to use Drupal.behaviors in Drupal 7?

Probably to late to load the js file in the .tpl try in template.php with

YOUR_THEME_preprocess_page(&$variables) {
  if ($variables['is_front']) {
    drupal_add_js(drupal_get_path('theme', 'mythemename'). '/js/test.js');
  }
}


Combination of textfields and checkboxes in a custom form

I ended up using a '#type' => 'container' instead of fieldset. And I used #prefix and #suffix in the children to add specific classes for spans and horizontal alignment etc.

One other thing that seemed useful but I ended up not using: template files for form theming. This is a very useful tutorial:

http://themery.com/dgd7/advanced-theming/forms/with-templates


I had to do this recently and found this solution using Drupal 9.1.
$file = File::load($fid);

$relative_file_url = $file->createFileUrl(TRUE);
$absolute_file_url = $file->createFileUrl(FALSE);

I found the createFileUrl() function in web/core/modules/file/src/Entity/File.php.  Maybe this would be considered "the way?"


Correct way of passing variables between hook and tpl.php

The arguments you pass to theme() when you invoke a theme function are not passed to hook_theme(), and from there to the template file. They are passed directly to the theme function, or the template file, in the case the theme function is using it.

hook_theme() defines the arguments used from the theme function. How those arguments are then passed to theme(), and to the theme functions, depends from the Drupal version:

With Drupal 7, they are all passed in an array, which in your case is similar to the following one:

array('forums' => $forum, 'topics' => $topic);

hook_theme() defines the default arguments used for the variables when no value is given. In your case, you could use array('forums' => $forum); and NULL will be used for 'topics'. (Replace $forum with the value you need to use.)
With Drupal 6, you pass the variable as single arguments to theme(), for example as in theme('search_products', $forum, $topic). As with Drupal 7, the default value is used when you don't pass that argument.

In both the cases, the variable declared for the theme function in hook_theme() is the name of the variable passed to the template file. In your case, $topics, and $forums are two variables accessible from the template file.

As side note, the template file you declare in hook_theme() with "template" for your theme_search_products() needs to be search-products, or search_products; Drupal will add the extension .tpl.php to the name, when looking for the template file. You cannot have a theme function that is declared as example_one, and the template file that declared to be example_two.
Also, you are trying to use theme_search_products(), but your hook_theme() implementation doesn't define that theme function. The code you are showing contains the definition for theme_main_reviews(). If the theme function you are calling is not defined from another module, that code will not work.


How to migrate content using a web service with multiple calls?

There is an issue with the UrlPerRow plugin above.

The source data isn't populated until after the check for whether the source data has changed. Because of that fact, it's always looking at previous data, which means the hash will never change, so "rowChanged()" never returns true. It will import new data but not update if the data changes.

A fixed version is below:

<?php

namespace Drupal\fad_migration\Plugin\migrate\source;

use Drupal\migrate\Plugin\MigrationInterface;
use Drupal\migrate\Plugin\migrate\source\SourcePluginBase;
use Drupal\migrate_plus\Plugin\migrate\source\Url;
use Drupal\migrate\Row;

/**
 *
 * @MigrateSource(
 *   id = "url_per_row"
 * )
 */
class UrlPerRow extends Url {

  protected $dataNewParserPlugin;

  /**
   * {@inheritdoc}
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, MigrationInterface $migration) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $migration);
  }

  /**
   * {@inheritdoc}
   */
  public function prepareRow(Row $row) {
    $prepare_row = parent::prepareRow($row);

    $item_info_settings = $row->getSourceProperty('item_info');
    if (!empty($item_info_settings)) {
      $this->getItemData($row, $item_info_settings);
    }

    if (!$row->getIdMap() || $row->needsUpdate() || $this->aboveHighwater($row) || $this->rowChanged($row)) {
      return $prepare_row;
    }
    else {
      return false;
    }

  }

  protected function getItemData(Row &$row, $settings) {

    $new_url = str_replace($settings['token'], $row->getSourceProperty($settings['token_replace']), $settings['url']);
    $this->getNewDataParserPlugin($new_url, $settings['item_selector'], $row->getSource());
    $this->dataNewParserPlugin->rewind();
    $xml_data = $this->dataNewParserPlugin->current();
    if (!empty($xml_data)) {
      $fields = $row->getSourceProperty('fields');
      foreach ($fields as $field) {
        if (!empty($field['item_info']) && !empty($xml_data[$field['name']])) {
          $row->setSourceProperty($field['name'], $xml_data[$field['name']]);
        }
      }
    }
  }

  protected function getNewDataParserPlugin($url, $item_selector, $settings) {
    $settings['urls']          = [$url];
    $settings['item_selector'] = $item_selector;

    $this->dataNewParserPlugin = \Drupal::service('plugin.manager.migrate_plus.data_parser')
                                        ->createInstance($settings['data_parser_plugin'], $settings);

    return $this->dataNewParserPlugin;
  }

}


I think this Node view count contrib module helps you.

Node view count

  Node View Count module allows to count node views. Unlike statistics
  module, this module records each view of node with user uid and
  timestamp. So now you can know how many times a user viewed node by
  day, week, month and etc.


Did you try any off the following module

Panels Page Cache

  This plugin can cache panels based on the path/url (arg() structure).

  This is needed if a panel has content which is dynamically per page
  (eg ad-tags, content related items).

Panels Hash Cache

  This module provides a hash-based cache for Panels and other Chaos
  Tools powered displays.
  This support caching based on any combination of:

Contexts (node, term, user etc)
Arguments
Drupal Path (args) (same as the Panels Page Cache Module)
Full URL (including domain and query string)
Users
Roles


If you want to modify the headers of a response, you need to use an EventSubscriber. Symphony doesn't have a hook system, but instead uses an event/emitter system. Since it's Symphony driving the request/response cycle, you basically needs to integrate with Symphony to do this.

You could take a look at \Drupal\Core\EventSubscriber\FinishResponseSubscriber to see how this is done, the gist of it is this:

/**
 * Add custom headers.
 */
class HeaderResponseSubscriber implements EventSubscriberInterface {
  public function onRespond(FilterResponseEvent $event) {
    $response = $event->getResponse();
    $response->headers->set('Some-Header', 'some value');
  }

  public static function getSubscribedEvents() {
    $events[KernelEvents::RESPONSE][] = array('onRespond');
    return $events;
  }
}

Note in the above code all use statements have been excluded, also you need to register your class as a event_subscriber service, this is done in your module's module_name.services.yml file like this:

services:
  name_of_service:
    class: Drupal\Full\Namespaced\Path\To\Class
    tags:
      - { name: event_subscriber }

You can add arguments (other services) that your class will depend on in the services file like normally.


You need to also to add the relation between the file to the current viewed groups with the OG membership relationship. You can have a look how this done in a view called "OG content"


Show data like tool tip when hovered over portion or regions on a custom map

What kind of map is it? An HTML imagemap (using  and  tags)? If so, you can use the EasyToolTip and MapHilight JavaScript libraries. They aren't connected to any Drupal modules, as far as I know.

EasyToolTip allows you to format the tooltips almost any way you want, and MapHilight allows you to highlight the section of a map that the mouse is hovering over.


Block configuration form values are not translated

You have to provide a schema in /config/schema/mymodule.schema.yml of the type block_settings.

Example:

block.settings.example_configurable_text:
  type: block_settings
  label: 'Example configurable text block configuration'
  mapping:
    block_example_string:
      type: text
      label: 'Block contents'

From the example module http://cgit.drupalcode.org/examples/tree/block_example/config/schema/block_example.schema.yml

Configuration values you map as type: label (single line of text) or type: text (multiple lines of text) are translatable.


How to make Ajax request from a drupal page?

Have look at jQuery.ajax():

$.ajax({
  method: "POST",
  url: "emailcheck.php",
  data: { email: "test" }
})
.done(function( msg ) {
  alert( "Data Saved: " + msg );
});

Also check your url. Your PHP file has to be in the same folder as your js file when you use relative paths.


How to have multiple columns for a single field in view

When you configure field in Views there is an option  Display all values in the same row  under Multiple field settings  uncheck that option. By doing this each image will display in separate column.


How do I prevent the feed aggregator creates blank nodes when cron is run?

Take a look at the Scheduler module. It creates blank nodes if you have some crappy nodes in scheduler table.


To use term names in a Contextual filter in Content views you need to add the Relationship to the taxonomy reference field you have in your content. Then you'll be able to add Taxonomy term: Name Contextual filter that will take names as arguments, and not term ID numbers.

You will be able to override the title for the Name contextual the same way, only use the corresponding token for the taxonomy name. You can look it up under Replacement patterns.

You can find more details about how to set up the Name contextual here in a section of this answer: Create view with path relative to taxonomy term


Taxonomy terms with associated nodes: display page by page navigation in node page?

For this you will have to use view module.

Step 1: Create a new view from Administration > Structure > View. Click on + Add new view.

Step 2: Give a name to your new view. From 'Show' select Taxonomy terms and from type select appropriate taxonomy vocabulary (I assume name is 'product' here). Check either page or block and click 'Continue & edit'.

Step 3: In First Page or Block under 'Filter Criteria' click on Add and select Taxonomy Vocabulary and set it to use product. Click on Add again from Filter Criteria and select Taxonomy term and set it to Parent term 1, Parent term 2, ..... Now in preview section you will see the Parent terms.

Step 4: Under FIELDS click on Add and select Taxonomy term: Term ID and click on Apply. In Configure field page check on Exclude from display and click on apply. (I assume Taxonomy term: Name is already there.)

Step 5: Rearrange the order of fields by clicking on drop down icon besides Add under FIELDS. Make user the Term ID appears above Term Name and Apply.

Step 6: Click on Taxonomy term: Term Name and expand REWRITE RESULTS. Click the checkbox Rewrite the output of this field and in text area name Text, type in [name] and Apply.

Step 7: Create a new page in same view +Add > Page or create a different view as in Step 1 & 2.

Step 8: In new view page set the path under PAGE SETTINGS to subchild/tid (here tid refers to parent tid or taxonomy id).

Step 9: Follow the steps 3 to 6. Instead of Parent term 1, select Child term 1.1, Child term 1.2, ... assuming Parent is 1. And set href to child/tid for step 6 here tid refers to child term 1.* tid.

Step 10: Follow the same procedure as in step 8 & 9 for other child terms.

Step 11: Follow the same procedure as in Step 8 to 10. However set path under Page Settings to subchild/tid and href attribute for step 6 would be product/tid, here tid is subchild tid or taxonomy ID.

Step 12: Follow the same procedure as in Step 11 for all subchild terms.

For Displaying Products:

Step 1: Create a new View from Administration > Structure > View. Click on + Add new view.

Step 2: Select Content from Show with appropriate type. Check on page and click on Continue & edit.

Step 3: Set the path in Page Settings to product/tid and from Filter Criteria select the Taxonomy term appropriate to the product to be displayed.


Need advice on how to setup a Drupal site on a given scenario

This is multiple questions, really, but here's a quick answer for you:

Part 1: Using Views, you can accomplish having multiple "pages" for a given node. You'll have all the data for those pages on the one "kate-winslet" node. Then you'll create a view that takes an argument from the URL. The path of the view will be entered something like this:
/celebrity/%1/movies-acted. You will need to add the fields you want to each view or view display. Then you'll add a contextual filter, using the node id. If this doesn't make sense to you, you just need to learn how to use Views, and particularly how to use contextual filters in Views.

Part 2: Yeah, you just need to view a tutorial on how to use Views. This is a simple View, but you'll need to use the views_attach module, too probably.


entity_uri() is an option, e.g.

$uri = entity_uri('node', $node);
$path = $uri['path']; // $path is e.g. node/1

$uri = entity_uri('taxonomy_term', $term);
$path = $uri['path']; // $path is e.g. taxonomy/term/1

It's best to use the API for this, even if hardcoding is an option. It's possible for the URI template for any entity type to be changed using hook_entity_info_alter, so you can't always guarantee it's going to be what came out of the box.


Display user picture below content type article

There is a module that comes with the Ctools module called Views Content Panes. Enable that. Also a good idea to enable the Context module, can be fetched here:
https://www.drupal.org/project/context

Views Content Panes is used to output Views as panel panes.

Import code for a View that will be a good starting point for your solution is provided at the end of this answer. This view will display the Article's author username and picture.

You may need to edit the "Argument input" setting in the view.

I set it to use the "From context" option, and the required context of Author.

This has a good chance of working immediately, but we may need to go further into your panels configuration if it doesn't.

After enabling the Views Content Pane module, and importing and saving the view, you will be able to add the newly created pane to your panel.

Import this view code:

$view = new view();
$view->name = 'user_name_and_pic_for_articles';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'users';
$view->human_name = 'User Name and Pic for Articles';
$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['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'none';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'none';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'fields';
/* Field: User: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'users';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['label'] = '';
$handler->display->display_options['fields']['name']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['name']['alter']['ellipsis'] = FALSE;
/* Field: User: Picture */
$handler->display->display_options['fields']['picture']['id'] = 'picture';
$handler->display->display_options['fields']['picture']['table'] = 'users';
$handler->display->display_options['fields']['picture']['field'] = 'picture';
$handler->display->display_options['fields']['picture']['label'] = '';
$handler->display->display_options['fields']['picture']['element_label_colon'] = FALSE;
$handler->display->display_options['fields']['picture']['link_photo_to_profile'] = FALSE;
/* Contextual filter: User: Uid */
$handler->display->display_options['arguments']['uid']['id'] = 'uid';
$handler->display->display_options['arguments']['uid']['table'] = 'users';
$handler->display->display_options['arguments']['uid']['field'] = 'uid';
$handler->display->display_options['arguments']['uid']['default_action'] = 'not found';
$handler->display->display_options['arguments']['uid']['default_argument_type'] = 'fixed';
$handler->display->display_options['arguments']['uid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['uid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['uid']['summary_options']['items_per_page'] = '25';

/* Display: Username and Pic for Articles Content pane */
$handler = $view->new_display('panel_pane', 'Username and Pic for Articles Content pane', 'panel_pane_1');
$handler->display->display_options['argument_input'] = array(
  'uid' => array(
    'type' => 'context',
    'context' => 'entity:node.author',
    'context_optional' => 0,
    'panel' => '0',
    'fixed' => '',
    'label' => 'Author: Uid',
  ),
);


Add custom link when using field_get_field

Problem with that module is that you have to define a token or fixed link. I am writing code that create a link on the fly, that can change in time.

For example: displaying the image of a taxonomy term, with a link to the last added node having this term.

The easiest solution:
$image = render(field_view_field(……));
$output = l($image, $link, array('html' => TRUE));I

When I tried this earlier it wasn't working, because by default the HTML option is set to false, displaying HTML code instead of rendered HTML code.


Using Rules How can I Remove a role from ANY user not just current user

A possible approach to make this work, is to process the results of a VBO enabled view via Rules, whereas your rule performs 2 Rules Actions:

load the VBO list of users that you want to be processed.
add a loop to perform a Rules Action, probably similar to the rule you already have in place, for each user contained in your Views results.

For more details, have a look at the tutorial "How to process the results of a VBO enabled view via Rules?".


Fatal error: Cannot redeclare casa_views_post_execute

I'm assuming you have two separate themes. Perhaps the theme in the casa_m directory is a subtheme?

If the machine name of the theme in the /case_m/ directory is casa_m , then change the function name to casa_m_views_post_execute(&$view)


How to add a CSS attribute to Image generated with image style

If you are comfortable overriding theme functions in your theme's template.php you can just create a YOURTHEME_image_style() function:

http://api.drupal.org/api/drupal/modules--image--image.module/function/theme_image_style/7


As long as you have something (a custom module, for example) looking for the arguments, yes, you can pass as many arguments as you want.

Depending on the size of the articles, however, instead of requiring a page refresh, I would suggest either an AJAX call (more complicated) or using jQuery (less complicated) to hide the content, and simply show it on demand. If the articles are large though, the jQuery option would be cumbersome and slow the page, since it would load all of the material at page load.


How can I get a list of all connected/logged in users?

You can try
// 3600s is one hour.
$uids = Drupal::database()->query('SELECT uid FROM sessions WHERE uid != 0 AND `timestamp` >=:time',[':time'=>(Drupal::time()->getCurrentTime()-3600)])->fetchCol();