# Question
Title: How to use Rules to transform upvotes and downvotes towards User Points?
I know that there is the Userpoints Karma module, and this is only updated to Drupal 6 version.

Are there any techniques for transforming votes towards User Points? Or can you point me in the direction of reference for creating a custom module for this purpose?

**Note**: The votingpoints module is not available for Drupal 7, so I was looking into using Rules to grant points to the creator of a node, when a user votes on it.

# Answer
> 3 votes
in these pages you can find what you need.

User Points This is a module

User Points Contributed modules more modules!

Choose the one that fits in your website.

# Answer
> 1 votes
# Question refinement

The Userpoints Karma module is indeed not available for D7. The purpose of this module was like so (from its project page):

> Userpoints Karma integrates the Vote Up/Down module with the Userpoints module to provide a node/comment rating karma system.
>
> The module allows a voter using the vote/up down widget to add or subtract points to the author of a given node or comment, thereby awarding or punishing the author for what they wrote. The number of points is configurable by the site's admin. Also, the node types are configurable, so that is shown on nodes or comments of a certain type, and not others.
>
> The module can notify users when they login with a total of points gained/lost due to others voting up their nodes or comments.

And this module depends on the Vote Up/Down module (which only has an alfa1 version for D7).

With all this in mind, for D7, I would recommend you to go for a combination of these alternative, and often used modules to achieve the same goal (= add (or subtract) user points when some node is voted up (or down)):

It's also the approach used in the Answers module (disclosure: I'm a co-maintainer of it), i.e. within its submodule "Answers Userpoints". If you agree, read on ...

# Required Rules

To handle all variations of voting, you need 4 rules (only!), which cover these 4 cases:

* a node is upvoted.
* an upvote for a node is canceled (= no longer upvoted).
* a node is downvoted.
* a downvote for a node is canceled (= no longer downvoted).

Below are the required rules, for each of these cases (use the Rules UI to import them in your own site, after you enabled the required modules mentioned above). These rules are enhanced versions of the rules included in the 7.x-4.0-rc2 version of Answers (and are expected to be committed to its dev version also). They use a content type with machine name `answers_question` (adapt this name to fit your own machine name).

### Upvote a node

The rule below will grant +5 user points for an upvote (to the author of the node):

```
{ "rules_voteup_question" : {
    "LABEL" : "voteup_question",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "answers" ],
    "REQUIRES" : [ "rules", "voting_rules", "userpoints_rules" ],
    "ON" : { "voting_rules_insert_node" : [] },
    "IF" : [
      { "node_is_of_type" : {
          "node" : [ "node" ],
          "type" : { "value" : { "answers_question" : "answers_question" } }
        }
      },
      { "voting_rules_condition_check_vote_value" : { "vote" : [ "vote" ], "value" : "1" } }
    ],
    "DO" : [
      { "userpoints_action_grant_points" : {
          "user" : [ "node:author" ],
          "points" : "5",
          "tid" : "0",
          "entity" : [ "" ],
          "description" : "Receive upvote to [node:type-name] \u0022[node:title]\u0022",
          "operation" : "QuestionUpvoteReceived",
          "reference" : "By uid=[vote:uid], for [node:type-name] to q=\u003Ca href=\u0022\/node\/[node:nid]\u0022\u003E[node:title]\u003C\/a\u003E",
          "display" : "1",
          "moderate" : "default"
        }
      }
    ]
  }
}

```

### Cancel the upvote a node

The rule below will grant -5 (= remove +5) user points for a cancelled upvote (to the author of the node):

```
{ "rules_voteup_question_cancel" : {
    "LABEL" : "voteup_question_cancel",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "answers" ],
    "REQUIRES" : [ "rules", "voting_rules", "userpoints_rules" ],
    "ON" : { "voting_rules_delete_node" : [] },
    "IF" : [
      { "node_is_of_type" : {
          "node" : [ "node" ],
          "type" : { "value" : { "answers_question" : "answers_question" } }
        }
      },
      { "voting_rules_condition_check_vote_value" : { "vote" : [ "vote" ], "value" : "1" } }
    ],
    "DO" : [
      { "userpoints_action_grant_points" : {
          "user" : [ "node:author" ],
          "points" : "-5",
          "tid" : "0",
          "entity" : [ "" ],
          "description" : "Unupvote [node:type-name] \u0022[node:title]\u0022",
          "operation" : "QuestionUpvoteCancelled",
          "reference" : "By uid=[vote:uid], for [node:type-name] to q=\u003Ca href=\u0022\/node\/[node:nid]\u0022\u003E[node:title]\u003C\/a\u003E",
          "display" : "1",
          "moderate" : "default"
        }
      }
    ]
  }
}

```

### Downvote a node

The rule below will subtract -2 (grant -2) user points for a downvote (to the author of the node) ... **AND** also -1 user point for the voter:

```
{ "rules_votedown_question" : {
    "LABEL" : "votedown_question",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "answers" ],
    "REQUIRES" : [ "rules", "voting_rules", "userpoints_rules" ],
    "ON" : { "voting_rules_insert_node" : [] },
    "IF" : [
      { "node_is_of_type" : {
          "node" : [ "node" ],
          "type" : { "value" : { "answers_question" : "answers_question" } }
        }
      },
      { "voting_rules_condition_check_vote_value" : { "vote" : [ "vote" ], "value" : "-1" } }
    ],
    "DO" : [
      { "userpoints_action_grant_points" : {
          "user" : [ "node:author" ],
          "points" : "-2",
          "tid" : "0",
          "entity" : [ "" ],
          "description" : "Receive downvote to [node:type-name] \u0022[node:title]\u0022",
          "operation" : "QuestionDownvoteReceived",
          "reference" : "By uid=[vote:uid], for [node:type-name] to q=\u003Ca href=\u0022\/node\/[node:nid]\u0022\u003E[node:title]\u003C\/a\u003E",
          "display" : "1",
          "moderate" : "default"
        }
      },
      { "userpoints_action_grant_points" : {
          "user" : [ "vote:user" ],
          "points" : "-1",
          "tid" : "0",
          "entity" : [ "" ],
          "description" : "Issue downvote to [node:type-name] \u0022[node:title]\u0022",
          "operation" : "QuestionDownvoteIssued",
          "reference" : "From uid=[node:author:uid], for [node:type-name] to q=\u003Ca href=\u0022\/node\/[node:nid]\u0022\u003E[node:title]\u003C\/a\u003E",
          "display" : "1",
          "moderate" : "default"
        }
      }
    ]
  }
}

```

### Cancel the downvote a node

The rule below will grant +2 (= remove -2) user points for a cancelled downvote (to the author of the node) ... **AND** also +1 user point for the voter:

```
{ "rules_votedown_question_cancel" : {
    "LABEL" : "votedown_question_cancel",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "answers" ],
    "REQUIRES" : [ "rules", "voting_rules", "userpoints_rules" ],
    "ON" : { "voting_rules_delete_node" : [] },
    "IF" : [
      { "node_is_of_type" : {
          "node" : [ "node" ],
          "type" : { "value" : { "answers_question" : "answers_question" } }
        }
      },
      { "voting_rules_condition_check_vote_value" : { "vote" : [ "vote" ], "value" : "-1" } }
    ],
    "DO" : [
      { "userpoints_action_grant_points" : {
          "user" : [ "node:author" ],
          "points" : "2",
          "tid" : "0",
          "entity" : [ "" ],
          "description" : "Cancel downvote to [node:type-name] \u0022[node:title]\u0022",
          "operation" : "QuestionDownvoteCancelled",
          "reference" : "By uid=[vote:uid], for [node:type-name] to q=\u003Ca href=\u0022\/node\/[node:nid]\u0022\u003E[node:title]\u003C\/a\u003E",
          "display" : "1",
          "moderate" : "default"
        }
      },
      { "userpoints_action_grant_points" : {
          "user" : [ "vote:user" ],
          "points" : "1",
          "tid" : "0",
          "entity" : [ "" ],
          "description" : "Withdraw downvote to [node:type-name] \u0022[node:title]\u0022",
          "operation" : "QuestionDownvoteWithdrawn",
          "reference" : "From uid=[node:author:uid], for [node:type-name] to q=\u003Ca href=\u0022\/node\/[node:nid]\u0022\u003E[node:title]\u003C\/a\u003E",
          "display" : "1",
          "moderate" : "default"
        }
      }
    ]
  }
}

```

# Reporting

Even though it may not be obvious from just browsing the (4) exported rules above, note the `description`, `operation` and `reference` used in each of the User Point transactions.

After you enabled the above rules and generated some (test) data with them (by voting on the nodes they relate to), go have a look at the typical User Points reports.

Here is an example of how it could look like:

```
Points Date                     Reason                          Status      Actions
   5   Fri, 04/01/2016 - 16:30  Receive upvote to Question ...  Approved   view edit
  -5   Fri, 04/01/2016 - 16:29  Unupvote Question "How to i...  Approved   view edit
   2   Mon, 03/28/2016 - 14:41  addPoints                       Approved   view edit
  -2   Mon, 03/28/2016 - 14:40  removePoints                    Approved   view edit
  10   Thu, 03/17/2016 - 13:52  Upvote Answer to "What are ...  Approved   view edit
   5   Tue, 03/15/2016 - 11:30  Upvote Question "How to imp...  Approved   view edit
  -5   Tue, 03/15/2016 - 11:27  Voting Corrected                Approved   view edit

```

---
Tags: 7, rules, userpoints, rating
---


# Question
Title: send emails to specific addresses based on value of fields
I have field\_a with select list of 10 value

when field\_b is checked and when a value of field\_a is alfa or beta or ecc, send email to address1 or 2 or ecc

I try with custom module for advance control of features

```
function test_mail_node_submit($node, $form, &$form_state) {
 if($node->type == 'rso') {
  if ($node->field_b['und'][0]['value'] == TRUE){
   if ($node->field_a['und'][0]['tid'] == '10'){
    mail('example1@mail.com', 'example2@mail.com', 'example text');
   }
  }
 }
}

```

I did not understand how to use drupal\_mail, or hook\_menu hook\_mail\_alter

# Answer
I am a little confused about your question. But here is an example for you to send email using hook\_mail. Hope you can get some idea from this:

```
/**
* Implement hook_mail() function
*/
function test_mail_node_mail($key, &$message, $params) {
   $headers = array(
     'MIME-Version' => '1.0',
     'Content-Type' => 'text/html; charset=UTF-8; format=flowed; delsp=yes',
     'Content-Transfer-Encoding' => '8Bit',
     'X-Mailer' => 'Drupal'
   );

   foreach ($headers as $key => $value) {
      $message['headers'][$key] = $value;
   }

   $message['subject'] = $params['subject'];
   $message['body'] = $params['body'];
}

/**
* Implement hook_submit() function
*/
function test_mail_node_submit($node, $form, &$form_state) {
   if($node->type == 'rso') {
     if ($node->field_b['und'][0]['value'] == TRUE){
       if ($node->field_a['und'][0]['tid'] == '10'){
          // mail('example1@mail.com', 'example2@mail.com', 'example text');
          $valid_email = array('example1@mail.com', 'example2@mail.com');
          $params = array(
             'body' => 'Your body text',
             'subject' => 'This is a subject',
          );
          drupal_mail('test_mail_node', 'HTML', $valid_email, 'en', $params));
       }
     }
  }
}

```
> 0 votes

# Answer
thanks for the reply.

I write this code:

```
function test_mail_mail($key, &$message, $params) {

 switch($key) {
    case 'one':
      $message['subject'] = "mail-1";
      $message['body'][] ="example text 2";
      break;

    case 'two':
      $message['subject'] = "mail-2";
      $message['body'][] = "example text 2";
      break;
  }
}

function test_mail_node_submit($node, $form, &$form_state){
    if($node->type == 'alfa') {
        if ($node->field_q['und'][0]['tid'] == '100'){
                $node->field_2['und'][0]['value'] = 'Mr.Brown';

// drupal_mail($module, $key, $to, $language, $params = array(), $from = NULL, $send = TRUE)
drupal_mail('test_mail', 'mail-1', '<example1.mail.com>', language_default(), $params, 'example2.mail.com');

        }
    }
}

```

it works but do not understand how to use $ params. In the Body of the Message I would like to insert some variable, for example: $node-\>field\_2\['und'\]\[0\] \['value'\] ((Mr.Brown))
> 0 votes

---
Tags: 7, emails
---


title: Ajax forms in pages

text:
# Question
Title: Ajax forms in pages
I am trying to code Drupal Ajax forms in Drupal pages (Drupal Content type: Basic page). However, it seems like the callback does not work, because when I remove the callback function nothing changes, and when I paste it back nothing changes.

Here is my code:

```
$the_ajax3_form = drupal_get_form('ajax_example_simplestt');
print drupal_render($the_ajax3_form);

function ajax_example_simplestt($form, &$form_state) {
  $form = array();
  $form['changethis'] = array(
    '#title' => t("Choose something and explain why"),
    '#type' => 'select',
    '#options' => array(
      'one' => 'one',
      'two' => 'two',
      'three' => 'three',
    ),
    '#ajax' => array(
      'callback' => 'ajax_example_simplestt_callback',
      'wrapper' => 'replace_textfield_div',
    ),
  );

  $form['replace_textfield'] = array(
    '#type' => 'textfield',
    '#prefix' => '<div id="replace_textfield_div">',
    '#suffix' => '</div>',
  );

  if (!empty($form_state['values']['changethis'])) {
    $form['replace_textfield']['#description'] = t("Say why you chose '@value'", array('@value' => $form_state['values']['changethis']));
  }
  return $form;
}

function ajax_example_simplestt_callback($form, $form_state) {
  return $form['replace_textfield'];
}

```

# Answer
> 1 votes
Your AJAX function callback is misspelled. This would be why it is not getting called.

Change `ajax_example_simplest_callback` to `ajax_example_simplestt_callback`.

Whichever spelling is correct, simplest or simplestt... Not knowing your context I do not know which it should be. But yeah, the function in the #ajax property is not defined in the context of this question.

---
Tags: ajax
---


# Question
Title: call a modules function from preprocess_page
I want to be able to call the current nodes taxonomy tree from page.tpl.php by using a function already in the taxonomy module. So far I've only been able to obtain the current nodes taxonomy id with:

```
$tid = $variables['node']->field_category['und'][0]['tid'];

```

I tried using: taxonomy\_get\_tree($tid);

but this only returns an empty array.

is there a way for me to use functions from other modules in \_preprocess\_page ?

full code:

```
function centro_preprocess_page(&$variables) {
     $tid = $variables['node']->field_category['und'][0]['tid'];
     $variables['taxTree'] = taxonomy_get_tree($tid);
 }

```

# Answer
> 1 votes
You are getting a taxonomy id. However, `taxonomy_get_tree` needs a vocabulary id as parameter, according to the documentation: https://api.drupal.org/api/drupal/modules%21taxonomy%21taxonomy.module/function/taxonomy\_get\_tree/7.x . That's probably why you are getting an empty array.

In order to be able to call taxonomy\_get\_tree, you would need to get the vocabulary id first:

```
$term = taxonomy_term_load($tid);
$vid = $term->vid;
print_r(taxonomy_get_tree($vid));

```

(see this question for more details about getting the vid from a tid).

---
Tags: 7, taxonomy-terms, hooks, theming
---


title: Entity Reference and Views

text:
# Question
Title: Entity Reference and Views
Actually, I am looking for a solution of entity reference module, I don't know whether its possible or not. Please let me know if its possible.

Example:

Content Type : A Content Type : B

Content type B (a field) referencing Content Type A,

So, if I want to make a list of content of content type A, which is referencing in content type B, I can do it with views and entity relationship.

But I am looking for a solution where I want to make a list of content of Content type A, which is not referencing in content type B yet.

Is it possible, if yes then how?

# Answer
This is really hard to answer with the information provided, but why not try adding a filter to your Filter Criteria in your View? In that filter make sure that you set the Relationship Field to the correct Entity Reference Field, the set the Operator to "Is empty (null)". That would filter Nodes which have no reference.
> 3 votes

---
Tags: views, entities
---


# Question
Title: How to show a message “field is required” from webform validation?
When a webform is validated it does not send the Drupal message "`X field is required`", it creates only the red border around the field.

How would I show the Drupal messages from triggering during validation? It is a block view of webform in drupal 7.

# Answer
> 1 votes
Webform Validation module can be used to add validation in field of webform.

# Answer
> 1 votes
Another powerful option is using 'Rules'. Install the 'Rules' module and the 'Webform Rules' and the 'Token' module.

Now we will create a custom Rule.

Go to /admin/config/workflow/rules

1. Click '+Add new rule'
2. Enter something in the 'Name' Field.
3. For the 'React on event' Field choose 'After a Webform has been submitted'.
4. On the next page you will see 'Conditions' and 'Actions'
5. Under conditions add the condition that generates the validation behavior
6. Under Actions click the 'Add an action' link. Choose 'Show a message on the site'
7. Under the 'Message' field write your message. You will see a 'Replacement Patterns' link/expand thing. Expand it and you will be provided with a ton of tokens that you can use to make a detailed error message based on available Fields.

# Answer
> 0 votes
you can implement hook\_form\_alter as implement below :

```
function YOUR_MODULE_NAME_form_alter(&$form, &$form_state, $form_id) {

    if ($form_id == "your_webform_id") {
       $form['#validate'][] = 'yourwebform_custom_validate';
    }
}

// Implement Callback
function yourwebform_custom_validate($form, $form_state)
{
    if ($form_state['values']['your_field_name']['und']['0']['value'] < 0) {

        form_set_error('your_webform_id', t('Your Error Message'));

    }
 }

```

# Answer
> 0 votes
According to the original question:

> "it creates only the red border around the field."

This would make it seem to me that `$messages` is not being printed out in the theme. That would be the first thing to look for in my opinion. The form is being validated but the messages from form\_set\_error are not being output.

If you are not using ajax, it is likely a good place to start.

---
Tags: 7, forms, webforms
---


# Question
Title: PluginNotFoundException: The "user" entity type does not exist
I am trying to return the common parent of 2 entities from their revision graph. For ex: 1-\>2-\>3-\>4-\>5 is a linear graph with 1 as original node and rest all are revisions. So, I wrote a function to take 2 revision ID as argument and return their parent (3 is parent of 4 and 5). The code is

```
<?php

namespace Drupal\conflict;

use Drupal\conflict\ConflictManagerInterface;
use Drupal\conflict\ConflictAncestorResolverInterface;

class ConflictManager implements ConflictManagerInterface {

    protected $resolvers = [];

    public function applies() {
        return TRUE;
    }

    public function addAncestorResolver(ConflictAncestorResolverInterface $resolver)
    {
         $this->resolvers[] = $resolver;
    }

    public function resolveLowestCommonAncestor($revision1, $revision2)
    {
        foreach ($this->resolvers as $resolver) {
            if ($resolver->applies()) {
                return $resolver->resolve($revision1, $revision2);
            }
        }
        echo "No revision found";
        return -1;
    }

    public function resolve($revision1, $revision2) {
        if ($revision1 < $revision2) {
            $par_revision = $revision1-1;
            return $par_revision;
        }
        $par_revision = $revision2-1;
        return $par_revision;
    }
 }

```

For this code, I have written a Kernel test:

```
<?php

namespace Drupal\Tests\conflict\Kernel;

use Drupal;
use Drupal\entity_test\Entity\EntityTest;
use Drupal\KernelTests\KernelTestBase;
use Drupal\conflict;

/**
* @group conflict
*/
class KernelLcaTest extends KernelTestBase {
   /**
    * Modules to enable.
    *
    * @var array
    */
   public static $modules = ['entity_test'];

   public function testsimple  () {
       $entity = EntityTest::create(['label' => 'revision 1']);
       $entity->save();
       $entity->label = ['revision 2'];
       $entity->save();
       $entity->label = ['revision 3'];
       $entity->save();

       $revision2 = entity_revision_load('entity_test', 2);
       $revision3 = entity_revision_load('entity_test', 3);

       $manager = Drupal::service('conflict.conflict_manager');
       $revisionLca = $manager->resolveLowestCommonAncestor($revision2, $revision3);
       $this->assertTrue($revisionLca->label() == 'revision 1');
    }
}

```

When i run this test through CLI with run-tests.sh, I get the following errors:

> Drupal\Tests\conflict\Kernel\KernelLcaTest::testsimple Drupal\Component\Plugin\Exception\PluginNotFoundException: The "user" entity type does not exist. /var/www/html/drupal8/core/lib/Drupal/Core/Entity/EntityTypeManager.php:125 /var/www/html/drupal8/core/lib/Drupal/Core/Entity/EntityManager.php:46 /var/www/html/drupal8/core/lib/Drupal/Core/Field/Plugin/Field/FieldType/EntityReferenceItem.php:66 /var/www/html/drupal8/core/lib/Drupal/Core/Field/BaseFieldDefinition.php:539 /var/www/html/drupal8/core/lib/Drupal/Core/Field/TypedData/FieldItemDataDefinition.php:66 /var/www/html/drupal8/core/lib/Drupal/Core/Field/FieldItemBase.php:50 /var/www/html/drupal8/core/lib/Drupal/Core/TypedData/TypedData.php:46 /var/www/html/drupal8/core/lib/Drupal/Core/TypedData/TypedDataManager.php:91 /var/www/html/drupal8/core/lib/Drupal/Core/TypedData/TypedDataManager.php:104 /var/www/html/drupal8/core/lib/Drupal/Core/TypedData/TypedDataManager.php:187 /var/www/html/drupal8/core/lib/Drupal/Core/Field/FieldTypePluginManager.php:82 /var/www/html/drupal8/core/lib/Drupal/Core/Field/FieldItemList.php:40 /var/www/html/drupal8/core/lib/Drupal/Core/TypedData/Plugin/DataType/ItemList.php:66 /var/www/html/drupal8/core/lib/Drupal/Core/Field/FieldItemList.php:118 /var/www/html/drupal8/core/lib/Drupal/Core/Field/FieldItemList.php:181 /var/www/html/drupal8/core/lib/Drupal/Core/Entity/ContentEntityStorageBase.php:112 /var/www/html/drupal8/core/lib/Drupal/Core/Entity/ContentEntityStorageBase.php:88 /var/www/html/drupal8/core/lib/Drupal/Core/Entity/EntityStorageBase.php:184 /var/www/html/drupal8/core/lib/Drupal/Core/Entity/Entity.php:509 /var/www/html/drupal8/modules/conflict/tests/src/Kernel/KernelLcaTest.php:22

Any kind of help would be appreciated. Thanks.

# Answer
> 3 votes
https://drupal.stackexchange.com/a/205919/42650 is related, specifically this part: "make sure the necessary modules are enabled".

In kernel tests, no modules are enabled by default. Anything, even required modules like user and system have to be enabled. That's one benefit of extending from EntityKernelTestBase as suggested there, that installs a bunch of things so you can have test entities with user references.

---
Tags: 8, debugging, testing
---


# Question
Title: How do I fetch the product display nodes referencing the given product using "Fetch entity by property"?
Let me start off by saying that I am ultimately trying to get the product display from a line item. I would use commerce\_rules\_extra, which has a feature that is supposed to do this, but I could not get it to work. So I am trying to get the product display node for the product.

My strategy is to create a simple Rules Component that returns all product display nodes that reference a given product.

My component accepts a parameter of type: Commerce Product

My component has a Condition: Data comparison: Product:type - equals - "Product"

My component has an Action:

* Fetch entity by property, Entity type: Node, Property: Product (I believe this is the product reference field)

When I attempt to set the Value as the component's Parameter "Product", the action will not accept this—instead it gives this error:

> The data type of the configured argument does not match the parameter's value requirement.

This would be the typical method for fetching nodes by property on an entityreference field but I can't do the same with this productreference field. Any hints would be greatly appreciated.

# Answer
Have a look at Action "Fetch entity by property" does not allow to fetch by multi-valued properties, which appears to be similar to what your question is about (and has RTBC status).

If I'm right, try the patch attached to it.
> 1 votes

---
Tags: 7, commerce, rules
---


# Question
Title: Set (add) group role using Rules when organic group membership is updated?
Using Rules, I am trying to set a users group role anytime a new membership entity is updated, however it appears roles are not brought into scope for me to set data value nor "grant og role"

All I want is

**Event:** After updating an existing og membership

**Action:** Grant OG role: Licensee (or set data value role: Licensee or whatever og centric things it asks for)

# Answer
> 3 votes
You should note that group role is not a field or property in the og\_membership entity. The og\_membership entity contains the properties etid, entity\_type, group\_type, and gid. There are other properties, but those are the ones you are interested in. When a user is added to a group, the entity\_type is user and the etid is the user id. When node content is added to a group, the entity\_type is node and the etid is the node id. The og\_membership entries are not updated very often, so I'm not sure why using the event "User has become a group member" isn't sufficient. Assuming you really do want to change a users group role when the og\_membership is updated, then you need to verify via rule conditions that the og\_membership group type is node and the og\_membership entity\_type is user. Then you can use the Grant OG Role action. The rule export would look something like this:

```
{ "rules_205092" : {
    "LABEL" : "205092",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "og" ],
    "ON" : { "og_membership_update" : [] },
    "IF" : [
      { "entity_is_of_type" : { "entity" : [ "og-membership:group" ], "type" : "node" } },
      { "entity_is_of_type" : { "entity" : [ "og-membership:entity" ], "type" : "user" } }
    ],
    "DO" : [
      { "og_grant_og_role" : {
          "account" : [ "og-membership:entity" ],
          "group" : [ "og-membership:group" ],
          "roles" : { "value" : { "licensee" : "licensee" } }
        }
      }
    ]
  }
}

```

---
Tags: rules, organic-groups
---


# Question
Title: Running module unit tests from CLI: "Class '..' could not be found"
I am trying to run module-provided PhpUnit tests from the CLI.

Following these instructions, so my core/phpunit.xml should be correct now.

Using this command:

```
cd core
../vendor/bin/phpunit modules/system/src/Tests/Installer/InstallerTranslationTest.php

```

I get this output:

```
Class 'modules/system/src/Tests/Installer/InstallerTranslationTest' could not be found in '/****/core/modules/system/src/Tests/Installer/InstallerTranslationTest.php'.

```

Module-provided tests in e.g. `core/modules/system/tests/src/..`, are found, and work correctly with the phpunit command. But tests in `core/modules/system/src/Tests/..` do not seem to work, or be detected.

(I think I had this problem before, and someone told me what was missing. But I don't remember anything. Time to document this in this Q/A site.)

# Answer
> 2 votes
Ok, so the solution is

From Drupal root directory:

```
sudo -u www-data php core/scripts/run-tests.sh --url http://d8.localhost/ --class "Drupal\system\Tests\Installer\InstallerTranslationTest"

```

Assuming that your site is available under http://d8.localhost, and it is an installed site.

Maybe you want to use `--verbose` for more output.

Documentation on drupal.org: Running Tests Through command-line

---
Tags: 8, testing
---


# Question
Title: Add on domain does not have access to "../privatefiles" at public_html level
I have a Drupal site that accepts private file uploads from some authenticated users.

The directory where those files are stored is *privatefiles* and it is located above the www directory, at the same level than the public\_html directory. In the file system, the private file system path is defined as "../privatefiles"

That seems to work well.

I But I am transferring the site to another hosting company and putting it there as an add on domain to an existing one. The uploaded private files are no longer visible.

To make the add on site, I had to create another directory. The new directory is *example1.com/example2.com* If I move the private file directory one level down (i.e. under the public\_html directory, then the private files become visible again.)

The only problem is that those files are now accessible from the web.

Does anyone know why this is so? How can I keep the private files at the same level? Should the *"../privatefiles"* be written differently? Or is this issue a limitation imposed by the new hosting company?

Any pointer for this would be greatly appreciated. :)

# Answer
> 0 votes
OK, I figured out what was going on and how to fix it.

The problem was indeed with the "../privatefiles" declaration for the private files directory. Just like for the old DOS files, the "../" means "one level up" and that is okay when the core file are in the www directory.

But when they are below or way below, the "../privatefiles" has to be replaced with the full path: "/home/whatever/privatefiles"

Now it works well.

---
Tags: files
---


title: commerce cart block with drupal theme

text:
# Question
Title: commerce cart block with drupal theme
I want to overwrite the block generated template drupal commerce "commerce cart" using the bootstrap theme. What I need is the name with which overwrite block.tpl.php theme for that specific block bootstrap

# Answer
> 1 votes
Edit your cart view and under Advanced, Theming: Information, click on Information and you will see this:

For template file name you want to use the last suggested name, (which I underlined for you) that way it only affects this specific view and not others.

Now that you have a name, click on the blue link and copy all the code in there and paste it into your template file and modify as you wish.

Remember to flush the cache to see changes or you could click the `Rescan template files` button

---
Tags: 7, blocks, theming
---


# Question
Title: Term Reference Autocomplete field that searches fields besides name
Is there any way to have a term reference autocomplete field search other fields than just the title? In my case I have a organizations vocabulary with the taxonomy name and an acronym. The main point of adding an acronym field is to stop users from putting in the acronym in place of the full organization name.

If I turned it into an entity reference field would, the autocomplete widget type allow me to do this?

# Answer
As far as I've been able to determine, there is no way to modify what autocomplete searches in a term reference field, though if seems possible, even likely that there might be a module or hook that does this, I didn't find it.

To answer my second question, yes, making this an entity reference enables the use of views to power the autocomplete, at which point you can handle the formatting and search fields of the autocomplete.

Better answers on this are very welcome!
> 0 votes

---
Tags: 7, entities, ajax
---


title: Auto Assign Role weight

text:
# Question
Title: Auto Assign Role weight
I am using Auto Assign Role Module to allow users to choose their role during registration. Block to choose role appears as first block, before the default fields (username, email and password).

Is there a way to move AAR block to the bottom, after the default fields?

# Answer
> 2 votes
Yes. You can reorder any Drupal form elements by altering its `#weight` property. To make the auto assign element appear above the other account registration elements just adjust its weight lighter.

This can be done in `hook_form_user_register_form_alter()` invocation:

```
/**
 * Implements hook_form_ID_alter().
 */
function MYMODULE_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  // Set the autoassignrole_user element 1 unit lighter than account form element
  $form['autoassignrole_user']['#weight'] = $form['account']['#weight'] - 1;
}

```

---
Tags: 7, users
---


# Question
Title: Where are the result and facet summaries for a search api view?
I had a solr search api search view all set up and working with the results showing properly, and an area at the top showing how many results had been found and what facets were applied with little links to cancel those filters.

Unfortunately I had to rebuild the entire thing because of a change in the content types in use.

Now I cannot figure out how to get that results/facets summary bar back. How do I get that?

# Answer
> 1 votes
What I was looking for was the Current Search Block which is a module that comes with facet api. It wasn't showing up for me because I needed to go into the block configuration, and update what search page it should appear on.

---
Tags: 7, search
---


# Question
Title: Contextual filter with hierarchical taxonomy terms
Using contextual filters, I have created a view which shows a page of users at us/california, based on a taxonomy I have made of locations.

This taxonomy is hierarchical, though, so when the user selects San Francisco, they no longer appear on the page.

I would like them to appear on both us/california and us/california/sanfrancisco.

How can I achieve this?

# Answer
> 0 votes
I remember working on the same type of issue while ago.

The point here is Drupal will store only the deepest taxonomy item you selected and not the whole taxonomy path.

I solved that by hooking the node\_save to save the whole path of taxonomy, but I'm not sure that's the best approach.

The other approach would be to find a way with views to make a join with the higher hierarchy level, by using relationships.

Another load could be to look at better\_exposed\_filter or hierarchical\_select

I hope it helps.

Cheers

# Answer
> 0 votes
**Simple hierarchical select**

This module does the trick for your need.

Install this module from the below link

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

After enable this module, got to your view and add filter criteria.

You can see Content: Has taxonomy Terms (Simple hierarchical select). Select that option and select your vocab. to filter.

Refer the screenshot.

By apply this you have filter criteria, check the url by apply those filter criteria.

Now make it display none and try to apply your taxonomy ids into this filter by try to make url like the one you get after apply filters.

No need to apply contexual filter, you can do that easily with filter criteria.

I hope this help you in your case.

---
Tags: 7, taxonomy-terms, views
---


# Question
Title: taxonomy terms view with custom alphabar (for Spanish)
I have a lot of views displaying taxonomy vocabularies with alphabar, the problem is that all the alphabar are by default showing the order for English alphabet, Spanish has ñ and accented letters, at both the alphabar as in the views, words starting with this letters are sent to the back, for instance, alphabar is like this:

* ......w | x | y | z | ñ | á | é | í | ó | ú

the ñ should be placed after n and those letters with accent shouldn't appear, they should be included within the corresponding unaccented letter

same for order in the view, for instance words are ordered like this (fictional words for the example)

* awto
* axma
* aypa
* azor
* años
* aísi
* aóko
* etc.

when correct order should be like this:

* aísi
* años
* aóko
* awto
* axma
* aypa
* azor

Any idea on how to solve this? Thanks in advance!

# Answer
I've been reading some documentation about character settings in mysql, and I have found a solution, I don't know if it's the right way for drupal, and it would not interfere with the taxonomy modules at update time in some way, I hope somebody could comment on this.... Anyway I just changed at the taxonomy\_term\_data table the collation of the "name" field to utf8\_spanish\_ci
> 0 votes

---
Tags: taxonomy-terms, paging, views
---


title: Creating a site with Drush doesn't work

text:
# Question
Title: Creating a site with Drush doesn't work
Trying to install Drupal 8 using drush.

```
drush dl drupal --drupal-project-rename=example
cd example

```

So far, so good.

However, when I get to this part:

```
drush site-install standard --db-url='mysql://root:my+Password@localhost/db_name' --site-name=Example

```

I've also tried:

```
drush site-install standard --db-url='mysql://root:my+Password@127.0.0.1/db_name' --site-name=Example

```

But I get the following error:

> Failed to connect to your database server. The server reports the following message: SQLSTATE\[HY000\] \[1045\] Access denied for user root@localhost (using password: YES) Is the database server running? Does the database exist or does the database user have sufficient privileges to create the database? Have you entered the correct database name? Have you entered the correct username and password? Have you entered the correct database hostname?

All of the answers are "Yes," so the install should work. Is it something wrong with my syntax? I have other Drupal sites on this server that I've installed manually, it's just the Drush install I can't get to work. What am I doing wrong?

# Answer
This one was tricky but I finally figured it out myself. The reason the installation was failing was because my MySQL password had special characters. Drush can't escape special characters, so I had to change the password using the following command:

```
mysqladmin -uroot -pOldPassword password newPassword

```

After that, it worked like a charm!
> 0 votes

# Answer
It is probably because you do not have a setting for the super user (user/1). You need to set the account user name and password, so you can login to Drupal.

```
drush site-install standard --account-name=admin --account-pass=12345 --db-url=mysql://dbusername:dbpass@localhost/db_name --site-name=Example

```
> 1 votes

# Answer
In your command you have not mentioned the mysql port. Please refer the following command.

```
drush si --db-url=mysql://db-user:db-pass@localhost:3306/db-name

```

Username and Password is optional, once the site is installed the auto-generated username and password will be provided on the console. Please note it carefully.
> 0 votes

---
Tags: 8, drush, installation
---


# Question
Title: How do I disable update checks for locked projects?
I am using `drush @sites cron` in order to get update notifications in a Drupal 7 multisite configuration.
However, I need to have some projects locked, using `drush up --lock=context_mobile_detect`.

Example:

```
.var.vhosts.drupalmulti#example.com           >>  Name                     Installed Version  Proposed version  Message
.var.vhosts.drupalmulti#example.com           >>  Context Mobile Detect    7.x-1.3            7.x-2.0-alpha1    **Locked via drush.**
.var.vhosts.drupalmulti#example.com           >>  (context_mobile_detect)                                       (Installed version not
.var.vhosts.drupalmulti#example.com           >>                                                                supported)

```

Since this command checks many sites, it sends many unnecessary emails of the form: "New release(s) available for example.com", although most of the time no module needs to be updated.

Is there a way, using code or not, to disable update checking of locked projects?

# Answer
> 1 votes
`drush cron` will trigger the default update manager search, whereas locked project are only locked during `drush pm-updatestatus`. If you want to prevent Update Manager from checking for particular modules, you'll need a custom module that implements `hook_update_projects_alter`. All you have to do then is `unset($projects['context_mobile_detect']);`.

E.g.

```
/**
 * Implements hook_update_projects_alter().
 */
function MYMODULE_update_projects_alter(&$projects) {
  unset($projects['context_mobile_detect']);
}

```

I do this quite a lot for Features modules, or custom code.

---
Tags: drush, updating, cron
---


# Question
Title: How to write a WHERE clause with the '=' operator using db_select()?
I have MySQL query as:

```
SELECT *
FROM `field_revision_field_innostream_state`
WHERE `field_innostream_state_tid` =187
LIMIT 0 , 30

```

How to write a WHERE condition within db\_select?

# Answer
> 3 votes
```
db_select('field_revision_field_innostream_state', 'innostream')
  ->fields('innostream')
  ->condition('innostream.field_innostream_state_tid', 187, '=')
  ->range(0,30)
  ->execute()
  ->fetchAssoc();

```

---
Tags: 7, database
---


title: Site behind a reverse proxy - subfolder

text:
# Question
Title: Site behind a reverse proxy - subfolder
We are using a public apache web server as a reverse proxy for to show a drupal instance (to the client). The website should come up in http://publicSite/path The Reverse proxy contains basic apache configuration pointing a "subfolder" to the internal webserver. Something like:

```
ProxyPass /path http://internaldomain/
ProxyPassReverse /path http://internaldomain/

```

The problem is that Drupal 8 has no longer a $base\_url and the site is broke (CSS, JS). Adding publicSite in the $settings\['file\_public\_base\_url'\] does not help. CSS/JS and links to themes are still broken.

There is a settings section on a Reverse Proxy in the settings.php, but it does not address the issue on accessing the website from a /subfolder url. Any hints to solve this issue!?

# Answer
You just need to reverse proxy all the asset directories like here (this proxies site preosasde via real site proreos):

```
ServerName preosasde

ProxyPass /themes/ http://proreos/themes/
ProxyPassReverse /themes/ http://proreos/themes/

ProxyPass /core/ http://proreos/core/
ProxyPassReverse /core/ http://proreos/core/

ProxyPass /vendor/ http://proreos/vendor/
ProxyPassReverse /vendor/ http://proreos/vendor/

ProxyPass /sites/ http://proreos/sites/
ProxyPassReverse /sites/ http://proreos/sites/

ProxyPass / http://proreos/asde/
ProxyPassReverse / http://proreos/asde/

```

Take care about the order of that entries and be aware that you will loose your users credentials (cause of the different domain).
> 1 votes

---
Tags: 8, uri, proxies
---


title: Dynamic Fields at content type level

text:
# Question
Title: Dynamic Fields at content type level
I got a site where we got pages tagged with several taxonomy terms. We also got several Contactblocks (added as Content Type & displayed by Views) that are tagged with the same set of taxonomy terms.

The Content Type "Contactblock" has the fields E-Mail, Phone & Room. Those Fields may vary from page to page. The reason behind this is some employees have different positions and those have to be displayed on different pages with different information. May way to go atm was to add multiple Contactblocks but its not clean enough for me.

My idea was to display for each tagged term a specific field of E-Mail, Phone & Room. But idk how the system can associate it then..

Atm its like ***page\<-\>taxonomy term\<-\>contactblock*** but it should be like ***page\<-\>taxonomy term, for each tax term\<-\>create fields: mail, phone & room***

Any idea how I can solve this? Any better idea is apreciated

# Answer
> 0 votes
Yes you can add fields: mail, phone & room to each of your tax terms, but the problem would be that all your employees would have the same mail, phone & room, because the fields belong to the tax term and not the employee. Unless you create a unique tax term for each of your employees this would work, but why do this when **page\<-\>contactBlock** will do the same?

So either you stick with **page\<-\>taxonomy term\<-\>contactblock**

or go with **page\<-\>contactBlock** using the Entity Reference module in D7 (for D8 Drupal Core already has this module's features). This option will save you save Database space since you don't create tax terms.

---
Tags: views, 8, entities, taxonomy-terms
---


# Question
Title: Assigning entity (node) to group (og) programmatically
How to assign an entity to a group programmatically? I have referred to this question however it doesn't seems to work:

```
$values = array(
    'type' => 'my_type',
    'uid' => $user->uid,
    'status' => 1,
    'comment' => 1,
    'promote' => 0,
);
$entity = entity_create('node', $values);
$ewrapper = entity_metadata_wrapper('node', $entity);
$ewrapper->body->set(array('value' => $form_state['values']['body']));
$ewrapper->save();
$result = og_group('node', $form_state['values']['group_id'], ['entity type' => 'node', 'entity' => $ewrapper, 'state' => OG_STATE_ACTIVE]);
$ewrapper->save();

```

# Answer
According to the API documentation, my code was missing an underscore character, and I should pass in the entity. So instead of

```
$result = og_group('node', $form_state['values']['group_id'], ['entity type' => 'node', 'entity' => $ewrapper, 'state' => OG_STATE_ACTIVE]);

```

it should be

```
$result = og_group('node', $form_state['values']['group_id'], ['entity_type' => 'node', 'entity' => $entity->nid, 'state' => OG_STATE_ACTIVE]);

```
> 0 votes

---
Tags: 7, entities, organic-groups
---


# Question
Title: How do I find out which module handle a GET/POST/PUT?
I'm reading a Drupal 7 project. However, unfortunately I can't find out which module handle an Ajax request. I only know the destination address which has been rewritten. (Suppose it's http://example.com/abc)

So, the problem is how could I find out which module handle my Ajax request?

# Answer
## Menu items (in code)

Drupal module register endpoint with `hook_menu()`. You can search the endpoint within the project, such as `abc`. It should stay inside `hook_menu()` with type `MENU_CALLBACK`.

You may find something like below.

```
function mymodule_menu() {
   $items = array();
   $items['abc'] = array(
     'title' => 'Ajax endpoint',
     'page callback' => 'mymodule_ajax_callback',
     ...
     'type' => MENU_CALLBACK,
   ),
   return $items();
}

```

## Menu items (in database)

In database, table `menu_router` saved all registered menu items. You can lookup the endpoint on `path` column and find the corresponding callback function on `page_callback` column.

## Modules

There is a number of module which provide UI or APIs for developer creating endpoints. Such as services and RESTful Web Services.
> 0 votes

---
Tags: 7, ajax
---


# Question
Title: Views with relationship of taxonomy terms
A node (Content 1) has two Tax-Terms (Category-Term 1, Category-Term2). The current relationship contains following entry: `term from field_category` and it's grouped via `field_category`.

How is it possible via a view to get this result?

* Category-Term 1
    + Content 1
* Category-Term 2
    + Content 1

But the current result is:

* Category-Term 1, Category-Term2
    + Content 1, Content 1

Thanks for help. Best C

# Answer
In your view FIELDS click on your Catagory field, since your category allows for multiple values, you should see the following option **Multiple Field Settings**, click on it to expand it:

All you gotta do is uncheck this.
> 1 votes

---
Tags: taxonomy-terms, views
---


title: CSS order in Drupal 8 libraries.yml

text:
# Question
Title: CSS order in Drupal 8 libraries.yml
From what I read about Drupal 8 themes there does not appear to be anything to order CSS file loading. As you know, CSS cascades down to a specific order when there is a conflict with an element. Since I have a class that is named the same as Twitter Bootstrap which is loaded from the CDN from the page.html.twig, I can usually modify a bootstrap class by having the CSS file that loads last as that can trump the bootstrap class that loads earlier. I have not discovered how to set an external library like Twitter Bootstrap in the libraries.yml file so it's in my page.html.twig file. So here is my THEME.libraries.yml

```
global-styling:
  version: 1.x
  css:
    theme:
      css/reset.css: {}
      css/style.css: {}
      css/htme-elements.css: {}
      css/tabs.css: {}
      css/messages.css: {}
      css/block-editing.css: {}
      css/wireframes.css: {}
      bootstrap/bootstrap.css: {}
      bootstrap/bootstrap.min.css: {}
      css/layout.css: {}
      css/default.css: {}

```

The default.css should load last which has the class I would like to override in bootstrap, but after

```
drush cache-rebuild

```

I find that the element is choosing the bootstrap element. OK, let me put the default.css element highest in the stacking order in case Drupal is putting in a different order. But after rebuilding my cache again, I find that bootstrap still "wins."

The closest thing in the Drupal docs was to perhaps add stylesheets-override in my THEME.info.yml

```
stylesheets-override:
  - system.theme.css

```

How should I set the order so that I can use the external Bootstrap files and load in my default.css last?

# Answer
You can create a separate library for external bootstrap stylesheet, which will give you flexibility to load bootstrap css before loading global-styling css. Here's how to do it:

**YOURTHEMENAME.info.yml**

```
# Defines libraries group in which we can add css/js.
libraries:
  - sp/bootstrap // ADDED - note: this should go before your global-styling
  - sp/global-styling
...

```

**YOURTHEMENAME.libraries.yml**

```
# note: bootstrap library should go before global-styling
# use { type: external } for external resources
bootstrap:
      css:
        theme:
         '//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css': { type: external }
global-styling:
      css:
    ...

```
> 5 votes

---
Tags: theming, 8
---


# Question
Title: How to create a view returning untranslated entities
I'm using entity translation and I want to create a view returning a list of **untranslated** nodes in the current active language. I have been searching all day but I cannot get this working...

# Answer
I do not think you can filter for untranslated nodes. It is not exactly what you are asking but the way I did it is this:
1. Create a Content View
2. Add the field which can be translated (e.g. Body)
3. Add the field "Entity translation: Body: translated"
4. Choose one language of the translation (e.g. Current User's Language)
5. Click "Rewrite the output of this field" and type "X" in the Text box
6. Click "No results behaviour" and type "-" in the Text box
7. Repeat steps 3 to 6 for other languages if you want to check multiple

This should produce a table with the first column being the source language and the rest of the columns corresponding to the different languages of the translations. When a record has been translated an X will appear, otherwise a - will appear.
> 0 votes

---
Tags: i18n-l10n
---


title: Pass video file

text:
# Question
Title: Pass video file
I create a REST server with Drupal 7, set everything and it work correctly, node created well, but I want to fill File field with REST.

my client side code is the following.

```
(function($){
  function getCsrfToken(callback) {
  jQuery.get(('http://example.com//services/session/token'))
    .done(function (data) {
      var csrfToken = data;
      callback(csrfToken);
    });
}

function postNode(csrfToken, node) {
  jQuery.ajax({
    url: 'http://example.com/rest/node',
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-CSRF-Token': csrfToken
    },
    data: JSON.stringify(node),
    success: function (node) {
      console.log(node);
    }
  });
}

var newNode = {
  type:'video',
  title: 'Example node title3',
  body: {
    und: {
    0: {
    value :"Body"}
       }
    },
  field_url:{
   und: {
     0: {
      value :"http://url.com"
    }
    }
    },
field_video:{
 ???????
 }
};

getCsrfToken(function (csrfToken) {
  postNode(csrfToken, newNode);
});
  })(jQuery);

```

How can I pass a file (or an image) to REST service? what should I write instead of `?????`?

# Answer
> 1 votes
You could upload the file first using the file:create\_raw services resource, which will return a file id (fid). Then you create your node and pass the fid in the file field {fid: "x}:

```
var data = new FormData();
data.append('files[file_1]', file);

jQuery.ajax({
    url: 'http://example.com/rest/file/create_raw',
    data: data,
    async: false,
    cache: false,
    contentType: false,
    processData: false,
    type: 'POST',
    success: function(result){
        alert(result);
    }
});

```

# Answer
> 0 votes
You will want to base64 encode the image file before you submit your document to the REST endpoint.

You an use https://www.base64encode.org/ to get an sample encoded image.

---
Tags: 7
---


# Question
Title: How do I include JavaScript with assets (libraries.yml)?
This is my `mytheme.libraries.yml` file:

```
global-styling:
  css:
    theme:
      css/style.css: {}

  js:
      js/effect.js: {}
    dependencies:
    - core/jquery

```

This is my `js/effect.js` file:

```
(function($) {
Drupal.behaviors.myBehavior = {
  attach: function (context, settings) {
      alert("Hello World");
  }
};
})(jQuery);

```

I created jquery.js in core folder of my site root. Even if I remove the dependency line from my libraries.yml and remove jquery syntax from my effect.js, I receive nothing on my site.

# Answer
> 3 votes
Most times it's about blanks. The yml files are very picky about this. Looks like your effects.js has 6 blanks instead of four.

And make sure, that you have your global-styling listed in the libraries section of your theme.info.yml.

---
Tags: 8, javascript
---


# Question
Title: How to allow content tagging by anonymous users?
I have a site, where the main purpose is the involvement of the public in their history. However, we all know some just don't want to register for a user profile with websites. In our case, there are some who would like to participate in tagging photograph nodes, without having to register.

So that is my question: how to allow anonymous users to tag photographs how they see fit, along with the obvious review process that would need to take place just in case? I've seen this feature on other sites, and have tried to contact the web admins, but have yet to hear back.

I know there is the module "Community Tags" and that works all fine and all but there are currently two problems I see with it (and if you know a solution that is staring me in the face, please let me know):

1. The anonymous users are allowed to post, but there is no review.
2. The tagging by the anonymous user does not sync at all with the only term reference field in the content type, so if I type one tag into one, it won't show up in the other. Both will post correctly to the list of taxonomy terms, but won't sync for the same page.

Any solution to my problem? Or maybe even an entirely better way of doing this altogether?

# Answer
> 2 votes
You could use the Flag module, and allow it to be used by anonymous users also, as described in my answer to "How to display a flag to anonymous users?". Create a flag for each tag you want to allow for anonymous tagging, and assume you label such flag like "Tag with TagABC".

Use the Rules module to create 2 Rules Components:

* a 1st Rules Component (say "Approve Tag suggestions") that performs 2 Rules Actions, and looks like so:

+ apply the tag TagABC
    + unflag it again (to remove the flag "Tag with TabABC").
* a 2nd (similar) Rules Component (say "Reject Tag suggestions") to only unflag (=remove the flag "Tag with TabABC") anything that is considered as "*rejected*".

Use the Views Bulk Operations (VBO) module (which depends on the Views of course) to create a VBO list of anything flagged like "Tag with TagABC", and use this during your review process to mark (select) anything that was flagged and that should be considered as "***approved***" (similar approach later on for anything to be considered as "***rejected***"). The actual "operation" to be performed (by VBO) is to execute either of both Rules Components described above. For more details on how you can use VBO and Rules together, refer to my answer to "How Do i implement an alternative for the Privatemsg Bulkmail module?".

4 commonly used modules (which can be used for plenty of other use case), and some relatively easy site configuration to be performed. That's it.

**Limitation**: what is above does NOT support FREE tagging (= invent your own new tags) for anonymous users (which may lead to tons of tags, used only once). Maybe a compromise could be to have a link to "suggest your own tag", via some form shown on a block? Other idea (never tried): flags are fieldable, so add a select list field to an extra flag (say: "pick your flag"), and use the "Select (or other)" module to allow such additional tag to be suggested.

---
Tags: taxonomy-terms, users
---


title: Create tpl file for webform

text:
# Question
Title: Create tpl file for webform
I have created a form using webform module. Is there any way to create tpl file for this form?

webform-form-node\_id.tpl.php is working fine. Here my problem is node\_id will deffer on dev,qa and production etc server.

Please suggest so that a single tpl file can used for all instance.

# Answer
You can use 'node--webform.tpl.php' template for all webform nodes.
> 3 votes

---
Tags: theming, webforms
---


# Question
Title: Userpoints Karma - Is it possible to only charge user points for down votes?
I'm using the User Points, User Karma, Vote Up/Down modules. I wonder if there is a way you can configure it to only deduct user points when you vote something down and not up.

Similar to Stack Exchange's reputation system: if you vote something up, you don't get docked, but if you vote something down you get docked reputation points.

Using the Reputation User Points -\> Karma Points -\> Voter Points Cost setting, I am only able to configure it to charge if you vote at all, regardless of the direction of the vote. Any ideas?

# Answer
> 5 votes
Adding a module to override User Karma's settings is certainly one option.

Another possibility is to use Rules and Voting\_Rules to control your own settings for adding and subtracting user points.

Once enabled you go to /admin/config/workflow/rules and "Add New Rule". Set it up to React on Event "User votes on a Node".

Add the condition "Check the value of the vote" and if less than 0 add an Action to "Grant points to a user" but make them negative points.

Here's a screenshot of this Rule:

Optionally, if you want to use User Karma in conjunction, you could instead React on the Event of "User was Awarded Points" and test for Conditions and override where appropriate.

# Answer
> 1 votes
For D7, I recommend to go for a combination of these alternative, and often used, modules to subtract (or add) user points when some node is voted down (or such downvote is removed again, which may happen too ...):

Below are the required rules, for each of these cases (use the Rules UI to import them in your own site, after you enabled the required modules mentioned above). Assumptions made in these rules:

* They use a content type with machine name `article` (adapt this name to fit your own machine name, or omit that Rules Condition to enable for any content type that can be voted on).
* The value of a downvote matches with "`-1`".

### Downvote a node

The rule below will subtract -2 (grant -2) user points for a downvote (to the author of the node) ... **AND** also -1 user point for the voter:

```
{ "rules_votedown_node" : {
    "LABEL" : "votedown_node",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "voting_rules", "userpoints_rules" ],
    "ON" : { "voting_rules_insert_node" : [] },
    "IF" : [
      { "node_is_of_type" : {
          "node" : [ "node" ],
          "type" : { "value" : { "article" : "article" } }
        }
      },
      { "voting_rules_condition_check_vote_value" : { "vote" : [ "vote" ], "value" : "-1" } }
    ],
    "DO" : [
      { "userpoints_action_grant_points" : {
          "user" : [ "node:author" ],
          "points" : "-2",
          "tid" : "0",
          "entity" : [ "" ],
          "description" : "Receive downvote to [node:type-name] \u0022[node:title]\u0022",
          "operation" : "DownvoteReceived",
          "reference" : "By uid=[vote:uid], for [node:type-name] to q=\u003Ca href=\u0022\/node\/[node:nid]\u0022\u003E[node:title]\u003C\/a\u003E",
          "display" : "1",
          "moderate" : "default"
        }
      },
      { "userpoints_action_grant_points" : {
          "user" : [ "vote:user" ],
          "points" : "-1",
          "tid" : "0",
          "entity" : [ "" ],
          "description" : "Issue downvote to [node:type-name] \u0022[node:title]\u0022",
          "operation" : "DownvoteIssued",
          "reference" : "From uid=[node:author:uid], for [node:type-name] to q=\u003Ca href=\u0022\/node\/[node:nid]\u0022\u003E[node:title]\u003C\/a\u003E",
          "display" : "1",
          "moderate" : "default"
        }
      }
    ]
  }
}

```

### Cancel the downvote a node

The rule below will grant +2 (= remove -2) user points for a cancelled downvote (to the author of the node) ... **AND** also +1 user point for the voter:

```
{ "rules_votedown_node_cancel" : {
    "LABEL" : "votedown_node_cancel",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "voting_rules", "userpoints_rules" ],
    "ON" : { "voting_rules_delete_node" : [] },
    "IF" : [
      { "node_is_of_type" : {
          "node" : [ "node" ],
          "type" : { "value" : { "article" : "article" } }
        }
      },
      { "voting_rules_condition_check_vote_value" : { "vote" : [ "vote" ], "value" : "-1" } }
    ],
    "DO" : [
      { "userpoints_action_grant_points" : {
          "user" : [ "node:author" ],
          "points" : "2",
          "tid" : "0",
          "entity" : [ "" ],
          "description" : "Cancel downvote to [node:type-name] \u0022[node:title]\u0022",
          "operation" : "DownvoteCancelled",
          "reference" : "By uid=[vote:uid], for [node:type-name] to q=\u003Ca href=\u0022\/node\/[node:nid]\u0022\u003E[node:title]\u003C\/a\u003E",
          "display" : "1",
          "moderate" : "default"
        }
      },
      { "userpoints_action_grant_points" : {
          "user" : [ "vote:user" ],
          "points" : "1",
          "tid" : "0",
          "entity" : [ "" ],
          "description" : "Withdraw downvote to [node:type-name] \u0022[node:title]\u0022",
          "operation" : "DownvoteWithdrawn",
          "reference" : "From uid=[node:author:uid], for [node:type-name] to q=\u003Ca href=\u0022\/node\/[node:nid]\u0022\u003E[node:title]\u003C\/a\u003E",
          "display" : "1",
          "moderate" : "default"
        }
      }
    ]
  }
}

```

Even though it may not be obvious from just browsing the exported rules above, note the `description`, `operation` and `reference` used in each of the User Point transactions.

Using such rules, the ***configuration*** of how much to charge for upvotes and/or downvotes is just a matter of adapting the values of the userpoints to be granted (or removed) using the Rules UI.

Also note the `description`, `operation` and `reference` used in each of the User Points transactions. That will also improve the typical User Points reports (via the various details added in the actual user point transactions).

Using the Conditional Rules module, you can consolidate these rules in a single rule also (which simplifies maintaining them).

**Homework**: adapt the rules shown above to implement something similar to bounties on SE (= transfer some amount of User Points from one user to another).

PS: "*if you vote something down you get docked reputation points*" (on SE) is only true for answers, not for questions. To refine that like you would want that to be, is just a matter of adding an appropriate extra Rules Condition (eg based on a content type of so).

---
Tags: userpoints, rating
---


# Question
Title: What causes the error in my custom module for OpenLayers 3?
This error gives me a whitescreen with just this message:

```
Drupal\Component\Plugin\Exception\PluginException:
Plugin (ifplabel) instance class "Drupal\ifplabel\Plugin\Style\ifplabel\ifplabel" does not exist in Drupal\service_container\Plugin\ContainerAwarePluginManager::getPluginClass()
(line 120 of /Users/me/Sites/ifp/html/sites/all/modules/service_container/src/Plugin/ContainerAwarePluginManager.php).

```

Background: The name of the module is called "ifplabel". I am making a custom module for OpenLayers 3 that will provide me with a custom marker style.

My Repo: https://github.com/joelhsmith/ifplabel

# Answer
> 0 votes
In human language, the error I am getting means:

> I see that you have provided a module, but I can't discover it in the location you indicated.

It could not find it because I told Openlayers to look for a Plugin/Control, but my module was actually implementing a Plugin/Style, which means I gave it the wrong namespace.

I fixed it on commit 3bfabab in my github repo https://github.com/joelhsmith/ifplabel.

I hope this example module will help others who are trying to make a custom marker style. It should work on any properly configured installation.

# Answer
> 1 votes
Looks like a mismatch between your annotation (the @ in the comment above your class) and your class declaration.

But you should post your code for more details.

---
Tags: 7, javascript
---


# Question
Title: What to do when saving nodes one-by-one and bulk resaving give different results
I'm using the Location Taxonomize module with the Address Field module to create a vocabulary of node locations.

I want to re-create the locations from scratch, and I have a term reference field attached to the node. This term reference field contains a reference to the automatically generated Location Taxonomize vocabulary.

The problem is, after I delete the vocabulary and term reference field and then re-create them, I cannot use VBO to re-save my nodes to automatically generate the Location Taxonomize terms and fill in the term reference fields. Instead, I have to save the nodes one-by-one, but there are 30,000+ nodes.

In other words: saving nodes individually works fine, but saving nodes in bulk does nothing.

The relevant code from Location Taxonomize Address Field submodule looks like this:

```
function location_taxonomize_af_element_submitted($form, &$form_state) {
  $lang = 'und';
  // Act on values
  $fields = $form_state['temporary']['addressfields'];
  $items = array();
  foreach ($fields as $field) {
    $deltas = $form_state['values'][$field][$lang];
    foreach ($deltas as $delta => $values) {
      // Don't process 'add more'.
      if (is_numeric($delta)) {
        // Add the Administrative Area name, if possible
        if (isset($form[$field][$lang][$delta]['locality_block']['administrative_area']['#options'])) {
          $options = $form[$field][$lang][$delta]['locality_block']['administrative_area']['#options'];
          $values['administrative_area_name'] = $options[$values['administrative_area']];
        }
        // Add the country name
        $values['country_name'] = location_taxonomize_get_country_name($values['country']);
        $items[] = $values;
      }
    }
  }
  // taxonomize
  if (!empty($items)) {
    location_taxonomize_taxonomize($items, $form, $form_state);
  }
}

```

As far as I can tell, this code is added by a submit handler, so when the nodes are re-saved using VBO, the submit handler is not called (I could be wrong about this; I am in over my head in this part of Drupal). What I want to do is force this bit of code to be called with VBO-- I know how to make a Rules action in code, but for nodes, that gives me the variable `$node`, not `$form`. **Is there some way to go from `$node` to `$form` to run this code? Or, is there some way to re-save a node in a bulk operation as if it were saved individually?**

# Answer
> 1 votes
You are correct that function is attached to the actual edit form when using the field, and therefore is bypassed during a VBO node save. This allows the function to be attached to any entity type that has the field (there are other ways to do this, but this approach was almost certainly easier than other options).

You can get from a node to a form using `drupal_get_form()` and providing the node as the form\_state:

```
$form = drupal_get_form('YOUR_NODE_TYPE . '_node_form', $node);

```

Note: *I have not tested that solution in your use-case.*

---
Tags: 7, forms, taxonomy-terms, rules, views
---


# Question
Title: Moved one site to another site files are refering old site
I moved whole Drupal setup from ex.(1.1.1.1 to www.example.com). After the move there are some issues. Some Drupal default files are not found error.(ex. close.png ,background.png) because the images references are for the old url: http://1.1.1.1/modules/overlay/images/background.png.

How can I fix that?

# Answer
First clear all caches. If that does not resolve the issue check your settings.php file(s) for references to the old address.

If you have images in content you can search the database tables for those fields to look for references (but fix them through Drupal's interface). Unless you have a huge number your better off fixing those one by one. Generally in D7 and before you want site or page relative image references not absolute references.
> 0 votes

---
Tags: migrations, multi-sites, configuration, xml-sitemap
---


# Question
Title: How to add custom badges depending on the amount of User Points earned?
In my website I have the Vote Up/Down module and the User Points module enabled and a rule (using Rules) to add user points for every vote automatically.

What is the way to add Custom Badges depending on User Points?

Let's say, if a user has 100-150 user points then the user's badge will be "Newbie". If the user has 150-200 points then the badge will be "Regular" and continues...

I have tried with the Achievements module but it seems difficult!

So what is the way to add custom badges depending on User Points?

# Answer
> 1 votes
Why not simply use the user\_badges module which explicitly integrates with userpoints?

> ```
> userpoints_badges
> Integrates Userpoints with the User Badges module.
>
> ```

Check out the userpoints contrib modules list, there may be more tools in there you can use..

# Answer
> 0 votes
If you don't have the required skills to use the Achievements module, or just don't want to do such coding (or don't want to hire somebody with such skills), then you may want to look at the Goals module (disclosure: I'm the maintainer of it) as a possible alternative. To start using it only requires typical administration tasks (configuration), though it does come with various hooks also for custom module development (if you want to).

To "*add Custom Badges depending on User Points*" (as in your question), this is what you could do:

* Define a goal for each badge you want to use. In your case these goals could fit:

+ Goal 1: "Receive the **Newbie** badge".
    + Goal 2: "Receive the **Regular** badge".
* Define the tasks it takes to complete Goal 1, something like "Gain at least 100 user points" (you could add more tasks if you want, but for your case only 1 would be sufficient). Define similar tasks to complete Goal 2 (something like "Gain at least 150 user points").
* Use the Rules module to capture the event that a user is granted user points, and add a Rules Action to "Record progress on a task" (add whatever Rules Condition if needed).

With the above configuration in place, Goals will then take care of checking which user completed which goal. And it also provides a Rules Event about "A goal completed by a user". Using that Rules Event, you can then perform whatever Rules Action that fits to grant the badge you want.

However Goals also allows for configuring an image for a goal. And it comes with a Views block which shows "Your completed goals". So you either use that image (if it fits your needs). Or you use the delivered view to create your custom version of it. Or you use some Rules Action to e.g. assign some badge using User Badges, similar to what is shown in my answer to "How to add a new user badge after earning a certain number of user points?".

For more details about the Goals module, including resources, etc, refer to my answer to "How to implement gamification in a Drupal site and award incentives?".

---
Tags: 7, users, rules, userpoints
---


# Question
Title: How to add predefined text to contact form?
I would like to add a couple paragraphs of predefined text (not an input field) to my contact page. What are my options to do this in Drupal 8? Until this point I've been using JS to get the job done.

# Answer
You can create a module, hook on hook\_form\_alter and add a #prefix to the first input field.

More simple: Create a block with your paragraphs and switch it on for region "(main) content" on the contact page (no programming needed).
> 5 votes

---
Tags: 8, emails
---


# Question
Title: How to adapt the name of a custom Drush command?
I saw the interesting answer to the question about "How can I get a list of content types with drush?", which starts like so:

> You can create a drush command named `content-type-list`.

But I wonder what it should look like if the command should be named something else, eg `mijn-contenttypes-lijst` (instead of `content-type-list`), and use drush `drush mcl` (instead of `drush ctl`)?

Some reasons why I may want to use another name:

* Because it conflicts with something else in Drupal for which I already used `content-type-list` and/or `ctl`.
* The command is hard to remember (eg because it's not in my native language), so I want to adapt it to another name.

What exactly would I have to change in the code included in that answer, which currently looks like so:

```
<?php
/**
 * @file
 * Drush commands related to Content Types.
 */

/**
* Implements hook_drush_command().
*/
function drush_content_types_drush_command() {
  $items['content-type-list'] = array(
    'description' => dt("Show a list of available content types."),
    'aliases' => array('ctl'),
  );
  return $items;
}

/**
 * Callback for the content-type-list command.
 */
function drush_drush_content_types_content_type_list() {
  $content_types = array_keys(node_type_get_types());
  sort($content_types);

  drush_print(dt("Machine name"));
  drush_print(implode("\r\n", $content_types));
}

```

PS: I understand I can create aliases for it also (as shown in the linked answer), but that's not what my question is about. E.g. if I want a command that does something different.

# Answer
> 6 votes
Using the code in my answer to "How can I get a list of content types with drush?", you can do something like this:

The name of your file is `MY_MODULE_NAME.drush.inc`

```
<?php
/**
 * @file
 * Drush commands related to Content Types.
 */

/**
* Implements hook_drush_command().
*/
function MY_MODULE_NAME_drush_command() {
  $items['MY-DRUSH-CMD'] = array(
    'description' => dt("Show a list of available content types."),
    'aliases' => array('MD-CMD', 'another-alias', 'and-other'),
  );
  return $items;
}

/**
 * Callback for the MY-DRUSH-CMD command.
 * See here that you must change the - by a _
 * (MY-DRUSH-CMD by MY_DRUSH_CMD) in the callback function
 */
function drush_MY_MODULE_NAME_MY_DRUSH_CMD() {
  $VAR = array_keys(node_type_get_types());
  sort($VAR);

  drush_print(dt("Machine name"));
  drush_print(implode("\r\n", $VAR));
}

```

In the aliases array you can add more aliases.

Install the module, run `drush cc drush` to clear the drush cache and use the command like this:

You can use:

```
drush MY-DRUSH-CMD
drush MD-CMD
drush another-alias
drush and-other

```

**References:**

# Answer
> 7 votes
You would have to change a couple of things:

```
/**
 * Implements hook_drush_command().
 */
function drush_content_types_drush_command() {
  $items['mijn-contenttypes-lijst'] = array(
    'description' => dt("Show a list of available content types."),
    'aliases' => array('mcl'),
  );
  return $items;
}

```

The array key under $items and the "aliases" value under that need changed. The array key is used to identify the callback to invoke when using the drush command or alias. The callback, for whatever reason, doesn't start with the command file prefix but rather starts with "drush" and then the command file prefix and then the array key listed above replacing the dashes with underscores. So the second (callback) function would look like...

```
/**
 * Callback for the content-type-list command.
 */
function drush_drush_content_types_mijn_contenttypes_lijst() {
  $content_types = array_keys(node_type_get_types());
  sort($content_types);

  drush_print(dt("Machine name"));
  drush_print(implode("\r\n", $content_types));
}

```

Making those changes should give you what you want. More information about creating your own drush commands can be found here: Command Authoring

# Answer
> 4 votes
See also the drushify command on drupal.org.

> drushify is a simple code generator that creates a skeleton Drush commandfile template for the module you specify.
>
> ### Installation
>
> ```
> drush dl drushify
>
> ```
>
> ### Usage
>
> ```
> drush @site drushify modulename
>
> ```

# Answer
> 3 votes
... Ill preface this by saying that your question really does make it sound like you should be creating an alais, but since you are explicitly asking how to create your own brand new command with a new name, here's what you can do:

You need to change the array key in the hook\_drush\_command function as well as the name of the callback function. You can create a file called drush\_foo and define any commands you want. Notice that the array key from the hook\_drush\_command function is the same as the callback function name (except hyphens are replaced with underscores). Try something like this:

```
<?php
/**
 * @file
 * Drush commands related to [insert description here].
 */

/**
* Implements hook_drush_command().
*/
function drush_foo_drush_command() {
  $items['mijn-contenttypes-lijst'] = array(
    'description' => dt("Do something awesome"),
    'aliases' => array('mcl'),
  );
  return $items;
}

/**
 * Callback for the mijn-contenttypes-lijst command.
 * Notice that this function name ends with mijn-contenttypes-lijst
 * except hyphens are replaced with underscores.
 */
function drush_drush_foo_mijn_contenttypes_lijst() {
  // Do something amazing (or call some other existing drush callback function)
}

```

Also, dont forget that whenever you add (or modify) a drush command you should ALWAYS run `drush cc drush` so that drush can clear its own cache and see that there is a new command

---
Tags: 7, drush
---


# Question
Title: How to reset Drupal's content cache / deleted content?
I'm working with Drupal 7.44. I created some content, but then deleted those articles. However, when I go to add new content, Drupal still recognizes the title of my articles that I deleted (as I'm typing it appears as an autocomplete below the field). I'm not sure if this is still completely stored in the database or if it's just cached somewhere. How do I go about deleting this (preferably without completely having to re-install everything)?

Administration -\> Configuration -\> Development -\> Performance and "Clear all caches" did not seem to work.

Thanks!!

# Answer
Unless you are using some module that I havent heard of (certainly possible) to give autocomplete style info as you are entering a node title, then I think the functionality you are describing is actually something being done by your browser.

You can alter your form to add automcomplete="off" to your title field (see https://stackoverflow.com/questions/2530/how-do-you-disable-browser-autocomplete-on-web-form-field-input-tag)
> 1 votes

---
Tags: 7, database, caching
---


# Question
Title: How to get higher weight range for vocabulary
I found the line in the taxonomy.admin.inc, but i didn\`t want to change it in the core. So, How can I get it in my module to override the #delta of the vocabularies?

With the function I didn\`t get a solution:

```
function <MYMODULE>_form_alter($form, $form_state, $form_id) {
  if ($form_id == "taxonomy_overview_vocabularies") {
    foreach ($form as $vocabulary) {
        if(isset($vocabulary['weight']['#delta'])) {
            $vocabulary['weight']['#delta'] = 20;
        };
    };
};

```

# Answer
> 1 votes
Remember to pass value by reference.

```
function <MYMODULE>_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == "taxonomy_overview_vocabularies") {
    foreach ($form as &$vocabulary) {
      if (isset($vocabulary['weight']['#delta'])) {
        $vocabulary['weight']['#delta'] = 20;
      }
    }
  }
}

```

---
Tags: 7, forms
---


# Question
Title: How to show 404 page for not found images
If I request an image that doesn't exist like mysite.com/test/test\_not\_found\_image.jpg, I get a Not Found white page just like this page: https://www.drupal.org/files/testing\_404.jpg.

Is it possible to have Drupal show the styled 404 page that I have instead of that white 404 page?

# Answer
> 0 votes
While @Shawn Conn's answer does work it does cause issues in Drupal because of image cache. If you go to a page that doesn't have the image style created yet it won't create the image because of the .htaccess rule.

The best way to display a 404 page on bad images is to use the Fast 404 module and create a static html page.

---
Tags: 7
---


# Question
Title: How can I use some Javascript to force a fieldset to stay open
How can some Javascript or CSS be used to keep a field set open when the page is refreshed?

I am using a module with a form in a fieldset that is automatically closed whenever the page is opened or refreshed. I don't want to touch the module code or write a module to fix it. Is there some Javascript or CSS that can be used to fix it, ie like CSS Injector or Javascript injector?

# Answer
You could definitely do that with some custom JS, but it might not be worth the trouble as there's a pre-built module which does what you need:

Fieldset collapser

> Whenever a user clicks on a collapsible fieldset header to toggle the "collapsed" state, the new state is being saved - uniquely for every form fieldset possible. Depending on the user's being registered with your site or not, this happens either in his user account data or locally on his computer using cookies.
>
> When the same form is called the next time, the fieldset states are restored to what they were last time. For registered users, this happens already on your server while preparing the form. Anonymous users will still see a little form animation by an invisible hand but then also be happy with their favorite fieldset states.
> 1 votes

# Answer
You should use `hook_form_alter()` and assign `FALSE` to `#collapsed` on the fieldset element.

Please read the Form API documentation for more details.

BTW, I love @Clive's answer more.
> 1 votes

---
Tags: theming, javascript
---


title: Twig Template for a Custom Block Plugin

text:
# Question
Title: Twig Template for a Custom Block Plugin
I'd like to have a custom twig template for custom block plugins from my custom module.

My custom block HeaderText contains

```
public function build() {
    return array(
        '#title' => 'Test',
        '#color' => $this->configuration['color'],
        );
}

```

It is located in myplugin/src/Plugin/Block/HeaderText.php

I have a template block--HeaderText.html.twig located in myplugin/templates which only contains test code

```
<h1>{{ title }}</h1><p>{{ color }}</p>

```

However the template isn't used. Following a guide I also added the following to myplugin/myplugin.module

```
function myplugin_theme($existing, $type, $theme, $path){
    return array('myplugin' =>
        array(
            'variables' => array(
                'title' => 'Default title',
                'color' => null
                ),
                'template' => 'block--HeaderText'
            )
        );
}

```

Which did not work either. And even if the previous code did work, I have multiple plugins within that module and that code seems to apply to every block which I don't want to do. I'd like each block to have a unique template.

# Answer
This issue I ran into was I did not specify '#theme' in the Block Plugin.

I added

```
public function build() {
    return array(
        '#theme' => 'myplugin',
        '#title' => 'Test',
        '#color' => $this->configuration['color'],
        );
}

```

and it worked
> 11 votes

---
Tags: 8, blocks, plugins
---


# Question
Title: Fatal error: Cannot redeclare THEMENAME_preprocess_page()
In D7, we have two copies of the same Bootstrap Agency base theme modified to show on different URLs using ThemeKey.

This works, but whenever a new module is installed, the site crashes and we see the following in the Apache error log:

`PHP Fatal error: Cannot redeclare bootstrap_agency_preprocess_page() (previously declared in /sites/all/themes/bootstrap_agency_minimal/template.php:13) in /sites/all/themes/bootstrap_agency/template.php on line 13`

This is actually a very similar issue to this , I just couldn't comment on the above and Clive's answer wasn't all that clear to me. Is it better to merge the two functions or rename one of them - as the 2nd answer suggests? And what does merging entail?

# Answer
> 1 votes
Function names in template.php have to be prefixed with themename\_function. At the same time, you cannot have a function declared twice.

`bootstrap_agency_preprocess_page()` should exist once in bootstrap\_agency/template.php, and the other should be `bootstrap_agency_minimal_preprocess_page()` in bootstrap\_agency\_minimal/template.php.

If you do not need to do any override, and the one theme is a subtheme, you can simply omit it from template.php. Otherwise, you would need to copy the function code in and amend what you need to amend.

---
Tags: theming
---


title: Non-Gregorian dates and calendars

text:
# Question
Title: Non-Gregorian dates and calendars
How can I use my native calendar in Drupal? I set Drupal to use Farsi and set Asia/Theran as default location, but the month names and years are still from the Gregorian calendar, even if they are translated in Persian.

Is there any coding method to use a calendar that is not the Gregorian one?

# Answer
> 2 votes
It is possible, but not currently in the queue for Drupal 8 core. There is nothing stopping it from being a contrib module, though, or being added to the Datetime Extras.

Essentially, the internals of Drupal are based around the PHP `\Datetime` class1, which uses the Gregorian calendar. Custom code would have to convert back and forth between this system.

I think two places would need to be updated:

1. Widgets would need to be created for timestamps and datetime fields to convert to the Gregorian calendar when a user enters a date. These widgets could then be configured every place fields are used (eg, via Manage Form Display).
2. A new date formatter service would need to be created to convert Gregorian dates to the other calendar system for when dates are rendered. The glitch here is that the date placeholders are baked into the field formatters in several places. New field formatters may also be needed to handle these cases. It would also be possible to just use new field formatters, but there are places in code that call out to the date formatter service directly (for non-field uses). Also keep in mind that there are places in core that don't use the date formatter service and call `format_date()` or `date()` directly (this is a known issue that will be addressed).

Also keep in mind that some things need to stay in the Gregorian calendar, and render out that way. The main place that pops into my head are where the ISO 8601 format is used, which happens in the RDFa module and when things like the HTML5 `<time>` element gets rendered out with the `datetime` attribute.

1 This is a *huge* simplification from how datetime and timestamps are handled by core, but the heart is still the native `\Datetime` class.

---
Tags: i18n-l10n, datetime
---


# Question
Title: Twig template variable not displaying value
I have a Twig template for a custom block. My custom module is establishing what template is used like so

```
function mymodule_theme($existing, $type, $theme, $path){
    return array('mymodule' =>
        array(
            'variables' => array(
                'header-title' => 'Default Title',
                'header-size' => 'h1'
                ),
                'template' => 'block--HeaderText'
            )
        );
}

```

and my custom block contains.

```
public function build() {
    return array(
        '#theme' => 'mymodule',
        '#title' => '',
        '#header-title' => $this->configuration['label'],
        '#header-size' => $this->configuration['header-size-submit'],
        );
}

```

And in my block--HeaderText.html.twig I have

```
<h2>{{ header-title }}</h2> This is a test {{ header-size }}
{{ dump() }}

```

However header-title and header-size both output 0. But using the dump() function in the template shows that the actual variables are available some how.

The dump() produces

```
array(15) { ["header-title"]=> string(19) "Header Textsdfgsdfg" ["header-size"]=> string(2) "h4"...

```

Yet {{ header-title }} just results in 0.

# Answer
> 2 votes
The issue was that Drupal didn't like that the variable names had hyphens in them. When switching from header-text to header\_text it worked fine.

---
Tags: theming, 8, blocks
---


title: Creating a layout with Page Manager

text:
# Question
Title: Creating a layout with Page Manager
I'm trying to use Panels and Page Manager in Drupal 8. My current versions of each are:

* Page Manager: 8.x-1.0-alpha23+12-dev
* Panels: 8.x-3.0-beta4+41-dev

My current problem is having no idea how to actually make a layout (layout\_plugin is installed.) I'm seeing this screen:

It doesn't matter what I change "Layout" to, the "Layout Settings" section doesn't change. I'm somewhat familiar with Page Manager in D7, and expected there to be some sort of layout manager in there, allowing me to choose panels/blocks/etc. I know there's a "Block Page"--and this would work for me--but in any of the tutorials, I've heard something about Block Page NOT being for production?

Nearly EVERY video/tutorial I've seen uses some other version of panels/page\_manager, and the look/structure has changed. So, I'm not sure if I'm doing this right or not, if it's broke, or if I just have no idea what I'm doing.

Panels, Page Manager and CTools was supposedly synced with their alphas last year, but they look like they've separated and I'm hesitant to use 5 month old versions of modules on a new release like D8 (particulary, CTools.)

# Answer
> 0 votes
Go to all recommended versions.

I was using different/more recent dev/alpha/beta versions of certain modules, but when I went to the recommended versions of...

* panels (8.x-3.0-beta4)
* page\_manager (8.x-1.0-alpha23)
* layout\_plugin (8.x-1.0-alpha22)

... everything seemed to work okay. This was as of 7-6-2016

---
Tags: 8, panels
---


title: Combining AND and OR in Rules

text:
# Question
Title: Combining AND and OR in Rules
I'm trying to set up a rule (using the Rules module) with AND and OR conditions. I have a content type with a field A (date) and field B (time slot).

The rule needs to check if field A is either e.g. a Monday or a Wednesday AND if the time slot in field B is either 16:00 or 17:00 or 18:00 or 19:00 (on a Monday) OR 13:00 or 14:00 or 15:00 or 16:00 (on a Wednesday).

If it meets those criteria it has to perform an action.

I've set up my rule as shown in the screenshot, but alas whatever combination or indentation I use, it won't work ...

Who can shed some light on this? Much appreciated.

# Answer
> 1 votes
You need 2 extra ANDs, right below the highest level (1st) OR.

And EACH of the 2 ORs you already have, and the Data comparison that preceeds those ORs, you need to move them below the extra AND. So that in the end it looks like so:

* OR
* + AND
* + - Data Comparison (A=Maandag)
* + - OR
* + - * Text Comparison (B=16:00)
* + - * Text Comparison (B=17:00)
* + - * Text Comparison (B=18:00)
* + - * Text Comparison (B=19:00)
* + AND
* + - Data Comparison (A=Woensdag)
* + - OR
* + - * Text Comparison (B=13:00)
* + - * Text Comparison (B=14:00)
* + - * Text Comparison (B=15:00)
* + - * Text Comparison (B=16:00)

Here is how "I" would translate the above logic:

* We accept a date that is either on Monday (line 2 to 8) OR (line 1) Wednesday (line 9 to 15).
* If you want a date that is a Monday (= line 3), we insist (via the AND in line 2) that you pick a timeslot that fits for us on Monday.
* To pick a timeslot for Monday, you have a choice (OR in line 4) of 4 options (ie those in line 5, 6, 7 or 8).
* Similar Rules, oeps rules, apply for Wednesday, as expressed in line 9 to 15.

If after these changes your Rules Action(s) still don't get executed (because something else is wrong in any of these Rules Conditions, and/or you're not using an appropriate Rules Event), then move on to Rules **debugging**, as explained in "How can I display the value of a variable inside a condition?".

PS: just to make sure your "*Text Comparison*" condition behaves as you expect/hope it to do, create a temporary clone of your rule with only 1 Rules Condition (= 1 such text comparison), with same Rules Event and same Rules Action. That way you can either narrow down your problem, or exclude that as a possible reason why it still doesn't work.

---
Tags: 7, rules
---


# Question
Title: Different taxonomy term title for menu and term page
Need help with one problem, I want to use different term title, 1-st for menu and breadcrumbs, 2-nd for term page

For example in menu and breadcrumbs: "doors" In term page: "glasses doors"

I thought create special field for alternative title and add to page.tpl but I don't know how I can do it.

Can anybody help?

# Answer
> 1 votes
You can use `drupal_set_title()` with implementing `hook_preprocess_page()`.

```
/**
 * Implements hook_preprocess_page().
 */
function mymodule_preprocess_page(&$variables) {
  $langcode = $variables['language']->language;
  $term = menu_get_object('taxonomy_term', 2, $langcode);
  if (!empty($term)) {
    drupal_set_title($term->custom_field[$langcode][0]['value']);
  }
}

```

`menu_get_object()` may not work because some module may override the menu entry `taxonomy/term/%` as mentioned by mxh.

If you want more robust way to retrieve the term object. Please use below snippet.

```
if (arg(0) == 'taxonomy' && arg(1) == 'term' && arg(2)) {
  $term = taxonomy_term_load(arg(2));
}
if (isset($term) && !empty($term)) {
  // code.
}

```

# Answer
> 0 votes
There a a lot of options to accomplish this. You have a few questions listed. Breadcrumbs can be a loaded question by itself. But Here is one option using the Menu Attributes module https://www.drupal.org/project/menu\_attributes you could fill in a Title attribute. Then If you are using Panels, you could override the page name by using a Token of the Name attribute. This would let your breadcrumbs and menu use the 1st title, while giving you a 2nd title.

# Answer
> 0 votes
Jimmy Ko get me right way

> You can use drupal\_set\_title() with implementing hook\_preprocess\_page().
>
> /\** * Implements hook\_preprocess\_page(). \*/ function mymodule\_preprocess\_page(&$variables) { $langcode = $variables\['language'\]-\>language; $term = menu\_get\_object('taxonomy\_term', 2, $langcode); if (!empty($term)) { drupal\_set\_title($term-\>custom\_field\[$langcode\]\[0\]\['value'\]); } }

But This not work for me ((( I think about it and my page.tpl code and found right variant.

```
function mymodule_preprocess_page(&$variables) {
    //  Check if taxonomy page
    if ( arg(1) == 'term') {

        //  load term data
        $term = taxonomy_term_load(arg(2));
        $title_term = $term->custom_field;

        //Check if custom field not empty
        if (!empty($title_term)) {
            // Set Custom Title
            drupal_set_title($title_term['und'][0]['value']);
        }
    }
}

```

For multilanuages site, maybe need this part of Jimmy Ko code `$langcode = $variables['language']->language;` and chahge 'und' to $langcode )

---
Tags: 7, views, taxonomy-terms
---