# Question
Title: How to debug a rule that doesn't want to fire?
I have nodes that can be flagged with a global flag. When a node is updated I want a rule to unflag that node.

* *Rules Event*: After updating existing content
* *Rules Action*: Unflag a node.

I then select the flag, "data selector" = node, "User on whose behalf to flag" = node:author (this field should be ignored because it's a global flag), "permission check" is unchecked.

When I update a node which has a global flag set, it doesn't get removed.

Did I set it up wrong? How can I debug a rule that doesn't want to fire?

# Answer
**Flag Module**

"User on whose behalf to flag" will not be ignored in this case.

When a flag is global, users don't necessarily have the required permission to toggle it. Be sure that the user role is allowed to flag or unflag the flag in question.

A nodes 'published' status is a good example of a 'global flag' (though it has nothing to do with the flag module.) When `published` is TRUE content is visible, when FALSE it's hidden. Though the flag is global, only those with the 'publish content' permission can toggle it. The Flag module works similarly.

---

**Rules Module**

Rules has a built-in debugger that is useful at times. It can be found at admin/config/workflow/rules/settings

---

I generally end up falling back on dd() or dpm() though when debugging rules. Rules is an incredible module for sure, but debugging at times can be a pain.
> 4 votes

# Answer
Rules is great, but sometimes also tough to debug if things don't work as you'd expect. There are some typical facilities to do such debugging (further detailed below), but a **K**eep-**I**t-**S**uper-**S**imple technique I often use, is my ***BINGO***-trick. A sample of such rule can be found in my answer to "Which Rules condition can be used to email a user when an admin updates their profile?". Stupid, but simple and efficient (I think).

If the above doesn't help, then there are typically 2 ways of more advanced debugging, as further detailed below.

# Rules Evaluation Log

Within the Rules **settings**, experiment a bit with the debugging facilities that come with the rules module. At least have a look at the "***Rules Evaluation Log***" (to check that the Rules logic being executed, actually matches what you expect that logic to be).

# Rules Action to display a value (using devel)

You may also want to (temporary) enable the Devel module, so that you can (temporary) add a Rules Action like "Display a value".

Obviously, make sure that there are no Rules Conditions that would prevent the rules Action(s) from being executed (if needed temporary remove such Rules Conditions).

# More info

For way more details about these 2 variations, refer to **Rules debugging**, as explained in the answer to "How can I display the value of a variable inside a condition?".
> 1 votes

---
Tags: 7, rules, flags, debugging
---


# Question
Title: In panels, does the right region get its argument from the left?
I plan to have a panel page with two regions:
\- on left, a panel of one author
\- on right, a view of all the stories written by that author.

I don't yet know how the user arrives at this page (my understanding of panels is still in its infancy).

Does the right panel get its argument from the left panel? Or somewhere else?

If the left panel node has Node ID 62, does the view (right panel) need to be sorted in node ID order (with a contextual filter)?

# Answer
It gets its context from the Contexts that you load into the Page on the Page Manager part of the dialog. It looks like this:

In this case I started to override the node view page, so it comes with the initial context of the node (nid, date published etc).

I then added a relationship on that same page of User to bring in the related Author's User data. After I saved it brought that context in for me and it looks like this:

**Note the User from Node part.**

I can continue to bring in context connected to the node, or now also connected to the user.

To embed a view in a Panels pane you need to first install **Views content panes** which is part of CTools. You then add a **Content Pane** via the Views UI to the view. You set the Contextual argument and in ADDITION you need to click on **argument input** (middle part of the Views UI) to tell the view where the context is coming from. This dialog will then bring up your contextual argument that you added, and a selection for you to specify where or what to get the context from. For the most part you will select **From Context** and for a node select Node, Content id. Now back in your Panels UI you can add a view as content. You select **View panes** (though this is just a default that is specified on the view itself and you can alter it per view), select your view, and it will pick up the contextual filter and the type of context you specified for it, and automatically make a selection of contexts that match that you have enabled in Page Manager.

So in order to decide what panel needs what context (or arguments) you need to first establish how the content in the specific panel is related to the type of page your are creating a variant for. I your case of author and stories, you can start with a user page and you want to end with stories on that user page written by the user. Your initial context will be User. No need to bring in extra context as your view for the right panel will take a uid contextual filter. Your right panel will embed a Views content pane with a contextual argument of uid that you connect as the author of the nodes. You will specify in that view that you want the argument input to be of User type from Context, and in your panel, when you add the content pane it will allow you to link it to the user context that is available.
> 1 votes

---
Tags: 7, views, panels
---


title: Get menu tail arguments of node route

text:
# Question
Title: Get menu tail arguments of node route
I saw in this post that D8 does not support the passing of extra menu arguments. Several posts on DA gives workable solutions, but they don't fit this use case.

The contrib module I am porting depends heavily on using those the extra arguments passed to on the route `/node/1/my_thing`. Adding my\_route causes a page\_not\_found error.

`my_thing` is not a tab but a parameter that generates content to merged into the view of the node.

As far as I know I cannot alter the behavior of core's route `entity.node.canonical`

# Answer
To answer my own question:

So in my case the route entity.node.canonical is not defined by my own module and although I want to use it in my module with an extra parameter, I don't want to mess with it.

I have chosen to use a query parameter (using ?) instead.

```
http://example.com/node/{nid}?id={id}

```

if you need the id you can get it from the request object:

```
$id = \Drupal::request()->query->get('id')

```
> 0 votes

---
Tags: 8, routes
---


# Question
Title: How to make commands invoked by drush_invoke not to fail after adding extra option?
I've added new option into drush command as suggested here:

```
function hook_drush_help_alter(&$command) {
  if ($command['command'] == 'features-revert-all') {
    $command['options']['cleanup'] = 'Remove non-existing components.';
  }
}

```

where `features-revert-all` is overridden by another created custom command as demonstrated here (so basically another `custom-features-revert-all` command is called).

However when my custom command invoking another commands via `drush_invoke` \- they fail, because they cannot find that option. I really don't care about the option whether they can recognise it or not, but they shouldn't fail.

So basically when I run:

```
drush fra --cleanup --yes

```

I've these errors:

> Unknown option: `--cleanup`. See `drush help features-cleanup-feature` for available options. To suppress this error, add the option `--strict=0`.
>
> Unknown option: `--cleanup`. See `drush help rules-revert-all` for available options. To suppress this error, add the option `--strict=0`.

Here is how my function look (simplified for clarity):

```
function drush_FOO_custom_features_revert_all() {
  module_load_include('inc', 'features', 'features.export');
  $force = drush_get_option('force');
  $cleanup = drush_get_option('cleanup'); // At this point, the option is working.

  $features_to_revert = features_get_features(NULL, TRUE);
  if ($cleanup) {
    drush_invoke("features-cleanup-feature", $features_to_revert);
  }
  else {
    drush_invoke("features-revert", $features_to_revert);
  }
  drush_invoke('rules-revert-all');
}

```

So basically the option works fine within the main function, but sub-commands are complaining that this option that it's unknown to them.

Question is, what's the correct approach of fixing it (so they won't fail)?

Do I need to add option to every other command which uses `drush_invoke` into `drush_help_alter`? Maybe there is some way of passing original drush options along. Or maybe I am forced to use `--strict=0`? Or there is some better way of fixing this issue?

# Answer
> 2 votes
The preferred solution is to use `drush_invoke_process()` for subtasks. This will execute the command in its own process, completely isolate from the parent.

If you do need or wish to use `drush_invoke()` (doing so is a little faster, since you don't need to bootstrap again), then you should use `drush_set_option('strict', 0);` to disable options checking.

---
Tags: hooks, drush
---


# Question
Title: Set the search index and the field_revision_body empty
I'm not using the core Drupal search engine and I'm not using any revisioning on my nodes. I noticed that the `{search_index}` table and `{field_revision_body}` table are occupying 50Mo of my database space.

Does emptying these tables cause any problems?

# Answer
> 3 votes
You shouldn't empty `field_revision_body` as it will break the content, but `search_index` is ok to empty.

Regarding search, please review the settings at: `/admin/config/search/settings`

e.g uncheck the Node and User search under "Active search modules"

# Answer
> 2 votes
As @DavidThomas mentions, doing a `TRUNCATE` or `DELETE FROM` on the `{field_revision_body}` table will cause bad things to happen. In short, your database will become inconsistent if everything related to a revision isn't deleted at the same time. If you don't need old revisions, you may want to take a look at the Node Revision Delete module. There are also other questions here about deleting old revisions.

Clearing out both `{search_dataset}` and `{search_index}` is mostly fine. If you look at the default profile for the Backup and Migrate module, you will see that the table structure (ie, the `CREATE` statements) is backed up, but the actual data isn't. However, these tables will then continue to grow when cron runs, because `hook_update_index()` will get invoked, and modules that implement search will index things, unless you deactivate them as @DavidThomas mentioned.

If you don't actually need search, though, disabling and uninstalling the core Search module is probably the best bet, though. Disabling the module will prevent the hooks from running, and uninstalling the module will remove all of the search tables from the database (the search module implements `hook_schema()`, so it manages its own tables, unlike some core tables that are handled by the system module).

# Answer
> 0 votes
Of note, even if you use Apache Solr or another search module, core will continue to index into the search\_index and search\_dataset tables.

You can disable that with this in your settings.php

```
// Disable core search indexing
$conf['search_cron_limit'] = 0;

```

---
Tags: database, search, nodes
---


title: Export block content in drupal 8

text:
# Question
Title: Export block content in drupal 8
I have made my custom block content. I created a block with it and I assigned it to a region.

How can I export the actual block content not the block type?

# Answer
One of these contrib projects:

* default\_content - for install profiles
* entity\_pilot - paas content staging (disclaimer, my product)
* deploy

Or build your own deployment with rest API
> 3 votes

---
Tags: 8, blocks, features, configuration
---


# Question
Title: How can I see the created date of a node in a view?
How can I see the created date of a node in a view? I don't see it as an option.

# Answer
> 0 votes
choose revision, created date as the field to add in the view

---
Tags: views, 8
---


title: Unable to clear cache

text:
# Question
Title: Unable to clear cache
I am facing an severe issue with Drupal instance. I am trying to clear the cache and the page is redirecting to error page.

This site can’t be reached The connection was reset. ERR\_CONNECTION\_RESET

Please help.

# Answer
Either drush cc or manually truncate cache tables in the db (Backup first!). Unsure if you are running Varnish, but if so you may want to manually flush this as well.
> 1 votes

---
Tags: caching
---


# Question
Title: No commerce_price field in product after Kickstart
I installed Commerce Kickstart 7.x-2.35 and I'm doing a Ubercart Commerce migration (from my current Drupal 6 site) using the Commerce Migrate Ubercart module. When migrating first products I don't see the prices and get an error message:

> Notice: Undefined property: stdClass::$commerce\_price en commerce\_product\_line\_item\_populate() in line 1394 of the commerce\_product\_reference.module.

During migration the old Ubercart price (`sell_price`) is correctly mapped to `commerce_price`.

When checking Product Display type I don't see any price field, the only fields I see are product title, url, body, category and reference. Should I manually add a price field `commerce_price`? How to do that?

# Answer
The commerce\_price field should be on products referenced by the display. Typically what happens is an importer will migrate all product entities first (which corresponds to each SKU in the remote system) and then set the product reference field value of a product display to point to those product entities. The SKU is unique, so it can be used as unique ID to reference displays to SKUs when you don't actually know product IDs.
> 0 votes

---
Tags: commerce
---


# Question
Title: Is there an Authcache load event for fragments?
I would like to create a callback javascript function to fire when one of my Authcache fragments is loaded via AJAX. Is there a way to hook into this event?

Thanks.

# Answer
> 0 votes
If you register your JavaScript as a *behavior*, then it is executed whenever the DOM changes, also when a fragment was loaded by authcache (see Managing JavaScript in Drupal 7). For example, the proper way to process any view - regardless of whether it is loaded via Authcache or not works something like this:

```
(function ($, Drupal) {
  "use strict";
  Drupal.behaviors.exampleModule = {
    attach: function (context, settings) {
      $('.view', context).once(function () {
        var view = $(this);
        // do something with view.
      });
    }
  };
}(jQuery, Drupal));

```

---
Tags: ajax, caching
---


title: How to use the Achievements module?

text:
# Question
Title: How to use the Achievements module?
I want to create some kind of challenges for users. And when it is fulfilled the user is able to unlock a new level and gain some kind of victory say in terms of a new theme, i.e, after completion of that challenge the user is awarded a new theme which the user can set as their theme.

I want to do this using the Achievements module. However there seems to be almost no documentation available, so I'm looking for ideas on how to proceed.

**Note**: I have basic understanding of php and have created few basic modules as described in drupal.org.

# Answer
The Achievements module is indeed a possible solution to implement the gamification facilities you are considering. However it does require Drupal development skills (you really need to write your own custom module for it).

If you don't have the required skills for it, 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 its maintainer) 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).

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

# Answer
The comments and example code in the documentation: achievements.api.php show how to create a new achievement.

There is no administration interface, you must create a module and use the hooks described in the above link to create new achievements.
> 4 votes

---
Tags: users, 7
---


title: User Folder Access Control

text:
# Question
Title: User Folder Access Control
I work at a university that has switched to Drupal. We have several hundred departments making their own "sites" in our system. Most departments need to be able to upload and change ONLY their own pdf files, images, and documents.

We can make folders for departments but no user will want to scroll through the list to upload something each and every time.

Can a folder system of some sort tie in to individual users or groups?

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

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

---
Tags: 7, users
---


title: Running Drupal API Scripts offline

text:
# Question
Title: Running Drupal API Scripts offline
I want to run some maintenance scripts against a Drupal 7 system. These scripts will call the Drupal API to use things like `EntityFieldQuery`, `node->save` and so on. I could create a module called `maintenance_scripts` which has a forms interface to launch the scripts with and to display their output, but I'd rather just run a script from the command line. Is this possible?

# Answer
> 4 votes
It is not necessary to write an entire Drush command just to run some php code. Use:

`drush php-eval '$a = callSomeFunction(); print $a;'`

or:

`drush php-script /path/to/script.php`

Drush will bootstrap your site and run your code.

---
Tags: drush, external-scripts
---


title: How to give ranking to content?

text:
# Question
Title: How to give ranking to content?
I have created a content type named **Ranking** and also created a field ***rank this content***. If I give rank 1,2,3 and so on.

Content should display according to rank, the content with rank 1 should show at first position and so on.

Any idea how to perform this?

**Note**: I'm using the Views module.

# Answer
You can achieve your requirement by following below steps.

1. Create view of **Ranking** content type.
2. Add fields you want to show to your listing.
3. Now add sort criteria of field **rank this content** with selecting **Ascending** operation.
> 4 votes

# Answer
You should indeed use the Views module as suggested in the prior answer.

However, to ***give ranking to content*** (as in your title), you could take this a step further. I.e. to automate the calculation of your "rank this content" field, by using the Radioactivity module. Some details about this module (from its project page):

> ... provides a field type which can be used as a hotness metric or a regular view counter for entities and for much much more. In essense, entities receiving attention (views or actions defined by Rules) are heated while inactive ones slowly cool down.

Refer to the article "Radioactivity 2: basics" for way more details / ideas about this very interesting module ...
> 1 votes

---
Tags: views
---


# Question
Title: How do I load the node create or edit form?
To load the login form I am using the following code.

```
$form = \Drupal::formBuilder()->getForm('Drupal\user\Form\UserLoginForm');

```

I would like to load the form to create or edit a node. How can I achieve this?

# Answer
Copying partially from an answer that I gave here: How to alter $form\_state before render a form?

To get an add form, you can have to do something like this:

```
$values = array('type' => $node_type);

$node = \Drupal::entityTypeManager()
  ->getStorage('node')
  ->create($values);

$form = \Drupal::entityTypeManager()
  ->getFormObject('node', 'default')
  ->setEntity($node);
return \Drupal::formBuilder()->getForm($form);

```

Edit: Somehow I missed that you said edit. You do exactly the same then, except that you don't create a new $node, you load the one you want to edit and then use that.

As written there, this is based on the entityblock\_form module, so if you need this in a block, you can also just use that module.
> 29 votes

---
Tags: forms, 8
---


# Question
Title: Start page count from 1 with views pager
Is there a way to start the page count from 1 instead of 0 using views pager? Maybe using aliases or some module?

By default, the first page is displayed with the URL parameter `?page=0`, the second page with `?page=1` and so on. The pagination works good, but in my opinion it would be more coherent having the page one for the url with the parameter `?page=1`, the page 2 with `?page=2`, etc.

I found a similar question here, but it's about Drupal 7 and I'm on Drupal 8: Views pager - start paging from 1

Another discussion here: https://www.drupal.org/node/1818040, but without a solution.

# Answer
To change it just on the UI, you can adapt the number in template\_preprocess\_pager in your theme's .theme file.

Something like:

```
function template_preprocess_pager(&$variables) {
  foreach ($variables['items']['pages'] as $key => $value) {
    $variables['items']['pages'][$key]['text'] = $key +1;
  }
}

```

To change the query params, you could use hook\_url\_inbound\_alter and hook\_url\_outbound\_alter to manipulate the queryparams, but this was D7. In D8 you would need to go in this direction to manipulate them: How do I implement the equivalent of hook\_url\_inbound\_alter()?
> 1 votes

---
Tags: views, 8, paging
---


# Question
Title: How to expose a persistent variable as a field for use in view
I have a particular base path recorded as a settings var, and I have a number of Views *(v3)* that unfortunately have this same value hard-coded as part of its links. These links are rendered using the `Rewrite results` and `Output this field as a link` options, and are built from a number of field values.

Problem is I have to configure this on every dev/test/prod site. **It would be far better if these links could pull the information from the persistent variable.**

A couple ideas:

* I have tried defining this value as a bespoke token, but as I expected these View options do not support checking for and rendering Tokens. I was hoping that perhaps using the global fields of the `Views Field View` module might work. So that I might render a field as `Exclude from display` and reference it with normal Views replacement patterns. However this failed to render Tokens as well.
* I could step into each specific field in question and override with a particular template, wrapping its content in the link and sourcing the variable directly with `variable_get`. But this would actually be quite involved, and would also remove the primary reason for using Views in the first place — the possibility of live modification.

**Is there a better way of using a persistent variable from within a View?**

I already have a bespoke module set up, so have looked to see if it is possible to modify the replacement patterns of a view with a particular hook or something; however that hasn't turned anything up so far. My last remaining idea is to hook into the final render of the view and perform a token pass, but I don't know if this is such a good idea or not.

# Answer
Your instincts are correct (and you're right about the lack of examples too).

In order to add a custom replacement pattern / token, you'll need to extend a Views field handler class and override the document\_self\_tokens() and add\_self\_tokens() methods. You can then instruct a field to use your custom field handler via hook\_views\_data\_alter() (thanks to Daniel Wehner for this info, and very likely the hook itself).

You can see example code from my need for adding a Views field replacement pattern / token.

If you need help adapting it for your need above provide the field or fields you'd like the replacement token to appear for and maybe more on how you'd like to construct it, but if you look at my example and remember to list in your .info the file with your field handler extending class so that Drupal registers it, you'll probably be all set.

(In giving the same answer over here, i also commiserated about the confusing naming of Views rewrite field replacement pattern "tokens" versus Drupal's Token API tokens.)
> 1 votes

# Answer
Just in case it is useful, I'll add another solution to this question — with a different perspective. The following needs to be placed in a bespoke module — with `HOOK` replaced by your module's name.

```
/**
 * Implements hook_views_post_render().
 */
function HOOK_views_post_render(&$view, &$output, &$cache){
  // enable token rendering only if this view has the right class
  if ( _HOOK_view_has_class($view, 'token-render') ) {
    // annoying little hack because a colon placed in a link
    // href seems to be filtered out by Drupal. so we aren't
    // able to formulate bespoke tokens properly. Instead
    // we write them slightly differently
    // i.e. replacing the colon with an underscore; and then
    // we rewrite them to be understood as tokens. Remove this
    // next line as you see fit.
    $output = preg_replace('/\[(HOOK)_([^\]]+)\]/', '[$1:$2]', $output);
    $output = token_replace($output, ($data = array()), ($options = array(
      'callback' => '_HOOK_filter_token_list',
      'clear' => TRUE,
    )));
  }
}

```

Also, just in case it is useful, here is the code to test that a view has a particular class. This isn't required, but I decided that I didn't want the extra processing all the time. So the above only functions if the view is given a class of `token-render`.

```
/**
 * Tests to see if a particular view has a particular class.
 */
function _HOOK_view_has_class(&$view, $class_name){
  if ( $view->display_handler ) {
    $classes = $view->display_handler->get_option('css_class');
    if ( !empty($classes) ) {
      $class_name = preg_quote($class_name);
      return preg_match('/(^|\s+)' . $class_name . '(\s+|$)/i', $classes);
    }
  }
  return FALSE;
}

```

Just for added security I wanted to make sure that only the tokens I wanted were being rendered. The following callback made that possible:

```
/**
 * Callback that controls exactly what tokens are allowed to be inserted
 */
function _HOOK_filter_token_list( &$replacements, $data, $options ){
  // blank anything that isn't allowed
  foreach ( $replacements as $key => $value ) {
    switch ( $key ){
      // this is just an example token key, add those you want to allow
      case '[current-page:title]':
        // the token was allowed
      break;
      default:
        $replacements[$key] = ''; // this token, wasn't
      break;
    }
  }
}

```
> 0 votes

# Answer
There is another rather clean way to do it - create handler just to return the variable. There's a blog post about this here.

It's pretty simple. In `MYMODULE_field_handler_VARIABLENAME.inc` file:

```
<?php

/**
 * Provide the VARIABLENAME variable to views.
 */
class MYMODULE_field_handler_VARIABLENAME extends views_handler_field {

  // No query to run here.
  function query() { }

  public function render() {
    return variable_get('VARIABLENAME');
  }

}

```

Then in `hook_views_data_alter()`:

```
$data['views']['VARIABLENAME'] = array(
  'title' => t('VARIABLENAME title'),
  'help' => t('Description of variable.'),
  'field' => array(
    'handler' => 'MYMODULE_field_handler_VARIABLENAME',
  ),
);

```

Now in your view you can add the field `Global: VARIABLENAME title`.

Don't forget to implement `hook_views_api()` in `MYMODULE.module` and add `files[] = MYMODULE_field_handler_VARIABLENAME.inc` to the `MYMODULE.info` file.

There are some shortcomings to this method though. You don't get everything that a normal field has because there is no table to join on. For example, the filter `Global: Fields comparison` doesn't work with it.
> 0 votes

---
Tags: 7, views, tokens, configuration
---


# Question
Title: How to get link path in custom block for a view?
I created a view (unformatted) associated with a content type with two simple fields for a block. The view is called "phrases" have generated two .tpl:

a) **views-view-unformatted--phrases-block.tpl.php** (to style row).

b) **views-view-fields--phrases-block.tpl.php** (to style the fields).

How to generate the link to the content, because by the variables I do not receive the direction I need.

I have available only the variable "$content", but this is formatted with something like:

```
<span class = "field-xx-xx">
     <a href="path/to/correct/content">Path</a>
</span>

```

I need to assign a class to the **"a tag"** , but as I receive all formatting can not.

Example i need:

```
<div class="my-class">
    <a class="my-link-class" href="path/to/correct/content">Path</a>
</div>

```

As I can generate the correct path to the content?

# Answer
In your view, in FIELDS add `Content: Path`

Then in **views-view-fields--phrases-block.tpl.php** add:

```
<div class="my-class">
    <a class="my-link-class" href="<?php print $fields["field_path"]->raw; ?>">Path</a>
</div>

```

if the above doesn't work try:

```
<a class="my-link-class" href="<?php print $fields["field_path"]->content; ?>">Path</a>

```

If the 1st and 2nd doesn't work, to make the 2nd one work, get rid off all your html markup, because it's probably printing as `href="<span>/yourpath</span>"`

Click on your Path field and unchecked add default classes.

In field settings, uncheck add field wrappers.
> 1 votes

---
Tags: 7, views, theming
---


# Question
Title: Notice: Trying to get property of non-object in function MY_MODULE_form_comment_form_alter()
I have an error Notice: Trying to get property of non-object in function MY\_MODULE\_form\_comment\_form\_alter() This error is related to the line if ($node-\>nid == $comment-\>nid) and I think to **$comment-\>nid**

I suppose that it is needed to describe $comment-\>nid as an object like for $node-\>nid an expression $node = menu\_get\_object() was used. I was searching for this similar program code and with no success. I have to use $form\['#attributes'\]\['class'\]\[\] = 'new-comment-form'; and that is why hook\_form\_alter is used. Maybe there is another solution to this problem?

The code is:

```
function MY_MODULE_form_comment_form_alter(&$form, &$form_state, &$comment_count, &$comment) {
    if (arg(0) == 'node' && is_numeric(arg(1))) {
      $node = node_load(arg(1));
      if (isset($node->uid, $GLOBALS['user']->uid) && $GLOBALS['user']->uid == $node->uid && $GLOBALS['user']->uid > 0) {
        $form['#attached']['css'] = array(
          drupal_get_path('module', 'MY_MODULE') . '/MY_MODULE.css.');
        }
    }

    $node = menu_get_object();

        if ($form['#node']->comment_count == 0 ){
        // hide a field
            drupal_add_css(drupal_get_path('module', 'MY_MODULE') . '/MY_MODULE2.css.');
        }

        if ($node->nid == $comment->nid) {
            $form['#attributes']['class'][] = 'new-comment-form';
        }

}

```

# Answer
You have the wrong function signature. It is supposed to be:

```
hook_form_FORM_ID_alter(&$form, &$form_state, $form_id)

```

In your function, $comment\_count is set as the form\_id, and $comment will always be null.

Set it to the signature above, then use $form\['nid'\] and $form\['cid'\]. To get the comment count on the node, inspect at $form\['#node'\]-\>comment\_count

Here is a replacement code for what you are trying to do:

```
function MY_MODULE_form_comment_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#node']->comment_count){
    // node has comments
    $form['#attached']['css'] = array(
        drupal_get_path('module', 'MY_MODULE') . '/MY_MODULE.css.', 'file');
  }
  else {
    // no comments on the node
    $form['#attached']['css'] = array(
      drupal_get_path('module', 'MY_MODULE') . '/MY_MODULE2.css.', 'file');
    $form['#attributes']['class'][] = 'new-comment-form';
  }
}

```
> 1 votes

# Answer
As said in the other answer, the hook signature is wrong, since the correct one is `hook_form_FORM_ID_alter(&$form, &$form_state)`. That is why you get an error about using a property for something that is not an object.

The rest of the code should be corrected too.

* `$form['#node']` contains the node object to which the comment is going to be attached. The following code can be simplified.

```
if (arg(0) == 'node' && is_numeric(arg(1))) {
  $node = node_load(arg(1));
  if (isset($node->uid, $GLOBALS['user']->uid) && $GLOBALS['user']->uid == $node->uid && $GLOBALS['user']->uid > 0) {
    $form['#attached']['css'] = array(drupal_get_path('module', 'MY_MODULE') . '/MY_MODULE.css.');
  }
}

```

I would rewrite it as follows.

```
if (!empty($form['#node']->uid) && !empty(GLOBALS['user']->uid) && $form['#node']->uid == GLOBALS['user']->uid) {
  // The node has been written from the currently logged-in user.
}

```
* You should not assume the comment edit form is shown in the node page. As long as you are changing the comment edit form, the page where the form is shown should not matter.
* The following code doesn't have sense. Even supposing your intention is to change the comment edit form only when it is shown in the node page, generally speaking, a comment is shown in the same page the commented node is shown.

```
if ($node->nid == $comment->nid) {
  // Omissis.
}

```

That condition would always be true.
> 0 votes

---
Tags: nodes, forms, comments
---


title: Migrate paragraph fields

text:
# Question
Title: Migrate paragraph fields
I have migrated Drupal 7 website to Drupal 8 version using the core migrate\_drupal\_ui module successfully but the paragraph module was broken upgrade path which results in final that the paragraph bundles not migrated and I have created in the new site like the old.

Now I need to migrate content for the paragraph fields only and update the nodes, I did some research and found possible solutions as follows:

1- Custom migrate plugin But I don't know how to edit existing.

2- custom script to read the nodes from other site by creating feeds and update.

```
//$nid get from feeds.
$entity = entity_load('node', $nid);

$entity->set('field_audit',
['field_number' => [0 => ['value' => 4]],
'field_regular_materials' => [0 => ['value' => '44']],
'field_verification' => [0 => ['value' => '444']]], FALSE);

$entity->save();

```

> That code gives error Fatal error: Maximum function nesting level of '256' reached, aborting!

what is the best practice to achieve.

# Answer
I would approach this differently. Using PHPMyAdmin or a Database viewer program, I would look at the Database for the paragraph fields table. Then just export table from D7 as a CSV file.

In D8, fill out 1 node paragraph values, just so you get the table structure, and export table as CSV.

Then with excel (or Libre office Calc) copy and paste values from one CSV to another.

Import CSV to D8 Database.

Clear the cache to see changes.
> 0 votes

---
Tags: entities, 8, migrations
---


# Question
Title: HTML tags removed during Views Rewriting
Hello I created a sitemap with the modules "Views and data export". The sitemap of my page works fine, but I would add images to my page.

The sitemap should look at first capture, I do a test with figure and they are well placed. When I "rewrite the results" the tag is ignored. How to implement these label ? it's been weeks since I'm on it.

Thank you

If I replace the HTML tags with text data it works:

However when I add HTML it gets removed:

---

I found answers to How add markup and prefix / suffix for computed field. Can you tell me how to put that in place?

# Answer
**HTML tags**, ugh, finally I understand your Q.

You can re-write your field using template files.

Go to `/sites/all/themes/YourTheme/templates` folder and

create **views-view-fields--\[view-name\]--\[machine-name\].tpl.php**

> For Example:
>
> If you view is called "Hello World" and the machine name is block\_1
>
> then it would be **views-view-fields--hello-world--block-1.tpl.php**

Inside your template file you put:

```
<?php

$fields["path"]->content = '<loc>' . $fields["path"]->content . '</loc>';

$fields["field_image"]->content = '<image:loc>' . $fields["field_image"]->content . '</image:loc>' . '<image:title>' . $fields["field_image-atl"]->content . '</image:title>';

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

```

When you are working with template files, **remember to clear/flush the cache** to see the changes.

Now your HTML tags should not get removed.
> 0 votes

---
Tags: 7, views
---


# Question
Title: How to pass variables to OpenModalDialogCommand
Drupal 8. Clicking the upload button on Form1 should open UploadForm in a modal dialog.

```
/**
 * Callback to display a modal.
 */
public function ajaxSubmit(&$form, FormStateInterface $form_state) {
  $op = $form_state->getTriggeringElement()['#return_value'];
  switch ($op) {
    case 'upload':
      $modal = new OpenModalDialogCommand(
        t('Upload file(s)'),
          render(\Drupal::formBuilder()->getForm('UploadForm',
            $this->nid, $this->foo, $this->bar))));
      break;

    // ... other cases.
  }

  $response = new AjaxResponse();
  $response->setAttachments($form['#attached']);
  $response->addCommand($modal);
  return $response;
}

```

I'm not able to pass the variables to UploadForm. `$this->` properties don't appear in UploadForm.

```
\Drupal::formBuilder()->getForm('UploadForm', $this->nid, $this->foo, $this->bar));

```

The form also fails if I replace the variables by local variables

```
$nid, $foo, $bar

```

But it works when I replace them by

```
'28', 'foo', 'bar'

```

The non-ajax version of the form uses a redirect to a form route (`my_module.uploadform`) and works OK. Is there a way to pass the parameters to UploadForm?

# Answer
> 2 votes
Solved. Thanks @kiamlaluno. I was convinced the variables were OK. But after your comment and a fresh look I saw what I was missing: `$this->nid, $this->foo, $this->bar` are optional parameters for the UploadForm formbuilder. I was passing only `nid` and `bar`, but missing `foo`, which messed-up things. So, instead of:

```
\Drupal::formBuilder()->getForm('UploadForm', $this->nid, $this->bar) //don't need foo

```

I needed to call:

```
\Drupal::formBuilder()->getForm('UploadForm', $this->nid, null, $this->bar)

```

A bit obvious, I'm afraid...

---
Tags: 8, forms
---


# Question
Title: What causes the errors in the rules that come with Commerce Coupon?
I am trying to use Commerce Coupon module in my project. The problem is after download and enable this module, rules created by this module got error. And I can't find out what happened to this errors.

* commerce coupon - 7.x-2.0-rc2+14-dev
* commerce version - 7.x-1.11+39-dev
* inline Conditions - 7.x-1.0-alpha7

Any suggestion is greatly appreciated.

# Answer
> 0 votes
A possible reason for running into this error is because the entity metainfo for "commerce\_coupon\_number\_of\_uses" is not provided, unless you have created a 'coupon type'.

In that case, try to create such coupon type and verify if it removes those errors.

---
Tags: commerce, rules
---


# Question
Title: How to set the filter condition by default for specific condition in view
How to set the filter condition by default for specific condition in view i,e i have view with the filter condition STATUS drop down list has 1\]live 2\] discard,so here i want to filter by default for live status when i open this view can any please tell me how to do this?

Thanks a lot in advance.

# Answer
> 0 votes
Use group filters, that way it will allow you to set a default.

---
Tags: views
---


# Question
Title: how to add custom additional password suggetions descriptions points in drupal 7?
I want to add few more suggestions points to existing password suggestions description in drupal 7 while registering new user. So tell me is it possible to modify it ?

# Answer
I have searched a lot for code and did lots of programming practices but nothing workout for me. Fortunately i got a module after searching whole day which fulfills my requirements. The module Password Policy

will define lots of constraints for setting password. Moreover, it also provide Delay constraint for specify minimum number of hours between password change and provide lot more. It works for me. Hopefully it also works for someone else.
> 0 votes

# Answer
Add this to your front-end theme's template.php file:

```
function THEME_form_alter(&$form, &$form_state, $form_id) {
  switch($form_id) {
    case 'user_register_form':
    case 'user_profile_form':
      $form['account']['mail']['#description'] .= "And some additional stuff.";
          break;
  }
}

```

Add similar to admin theme if need be.

Clear the cache when you are done.

Alternatively try Better field descriptions.

> Better field descriptions makes it possible to add themeable descriptions to fields in forms.

I have never tried it but it looks like it could do the job, through just adding your own form\_alter hook is much simpler.
> 1 votes

# Answer
You can edit any form by creating your own module and invoking hook\_form\_alter().

```
function YOURMODULE_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'user_register_form') {
        $form['account']['mail']['#description'] .= "your custom text";
    }
}

```

You may have to disable and enable the module and clear the cache.

Note that if your site is multilingual, you will also have to update your translations accordingly.
> 1 votes

---
Tags: 7
---


# Question
Title: How to add a 3rd party library and call it using Libraries
I've installed the Libraries module. How can I add a 3rd party PHP library in my Drupal 7 project. How do I use `hook_libraries_info()`?

# Answer
The Libraries project page has good documentation on how to use version 2.x API. Essentially, there are 2 components to it.

You're defining an implementation of `hook_libraries_info()`, that returns an array that defines the library's machine name, resources to load, & a means to validate the library version (either an `version arguments` element that defines the array passed to `libraries_get_version()` or a custom `version callback` function).

```
/**
 * Implements hook_libraries_info().
 *
 */
function MYMODULE_libraries_info() {

  // Define 'simple' as the machine name of library
  // which will be stored in sites/all/libraries/simple
  $libraries['simple'] = array(

    // This gets passed to the $options array in libraries_get_version()
    'version arguments' => array(
      'file' => 'simple.js',
      'pattern' => '/Version (\d+)/',
      'lines' => 5,
    ),

    // Alternatively, MYMODULE_version_callback could be defined.
    // this function returns TRUE/FALSE if it finds a valid version of the library
    //'version callback' => 'MYMODULE_version_callback',

    // Defines the PHP,JS,CSS files to load for the library
    'files' => array(
      'js' => array('simple.js'), //this can be a path to the file location like array('lib/simple.js')
    ),
  );

  return $libraries;
}

```

The 2nd component is to load the library using `libraries_load()` wherever you need in your module.

```
//Load the 'simple' library
libraries_load('simple');

```

See the linked documentation for more information.
> 0 votes

---
Tags: 7, theming
---


# Question
Title: How to assign user ranks based on their userpoints?
I am using the User Points and User points Nodes and Comments modules to calculate user points when they publish an articles or comment on a node.

On these points I want to assign some rank to the user. Like for example

```
    Upto 100 – Junior Member
    100 to 300 – Senior Member
    300 + - Premier Member

```

Can someone give me some idea about this?

# Answer
Your question seems like a perfect usecase for the Goals module (disclosure: I'm its maintainer). It can be used in combination with the userpoints module, though you'd use that combination by granting user points "after a goal is completed".

Here is a possible configuration for your specific case:

* Define 3 **goals** like so:

+ Junior Member
    + Senior Member
    + Premier Member
* To achieve *goal* "Junior Member", define the **Task(s)** to be completed. E.g.:

+ Publish 1 (or some other amount of) articles.
    + Post 1 (or some other amount of) comments.
* To achieve *goal* "Senior Member", define the **Task(s)** to be completed. E.g. publish 10 articles and post 20 comments.
* To achieve *goal* "Premier Member", define the **Task(s)** to be completed. E.g. publish 25 articles and post 50 comments.
* Write the appropriate rules, using the Rules module, to track process on completing the various tasks. Basically you'd only need 2 (extremely basic) rules, which would be triggered like so:

+ After publishing an article.
    + After posting a comment.

Note that these very 2 rules can be re-used to measure progress on each of the 3 rules. If you want, you could expand these rules (with an extra rules action) to also assign userpoints, to implement your userpoints design you have in mind.

Refer to my answer to "How to implement gamification in a Drupal site and award incentives?" for way more details about the Goals module.

Note: Using Goals only requires typical administration tasks (configuration), though it does come with various hooks also for custom module development (if you want to).
> 2 votes

---
Tags: userpoints, 7
---


# Question
Title: Organic Group: Can not create group type content?
I have *Organic Groups* installed on my website. I have a content type with OG setting as **Group**. I had several contents of this type. And then all of a sudden, I started getting the following error when I try to create a content of this type:

`Can't save entity as group, because user admin can't be subscribed to group and become a manager.`

What may be causing this error?

# Answer
> 1 votes
You should change the number of value for the group\_group field to unlimited. That field must be in the content type which you defined as group.

# Answer
> 1 votes
In my situation, it was caused by a recently deleted group still in the og\_membership table. I had og field access enabled, and it was trying to determine if I had rights to write to the fields within the group. It didn't recognize the new node being created, so og searched through other groups my user was a member of to learn of my field rights. It saw a group in og\_membership that technically didn't exist, and returned FALSE instead of null.

Anyway, this patch may help you: https://drupal.org/node/1538658#comment-8182821

Try it out! Disclosure: it's my patch :) If it works for you, make a comment in the drupal issue queue saying so.

# Answer
> 0 votes
**Solution:** Go to Configuration \> People \> Account Setting \> Manage Fields \> Edit Group membership Field \> Scroll down to GROUP *MEMBERSHIP FIELD SETTINGS* and Make Number of value **Unlimited** \> Save and Enjoy

---
Tags: organic-groups
---


title: Add tab / local task to a node

text:
# Question
Title: Add tab / local task to a node
I've created a module called `hotel_reviews`.

I've created the route node/{node}/reviews using hotel\_reviews.routing.yml.

```
hotel_reviews.content:
  path: '/node/{node}/reviews'
  defaults:
    _controller: '\Drupal\hotel_reviews\Controller\ReviewsController::content'
    _title: 'Reviews'
  requirements:
    _permission: 'access content'

```

I then tried to add a local task using hotel\_reviews.links.task.yml.

```
hotel_reviews.content:
  route_name: hotel_reviews.content
  title: 'Reviews'
  base_route: node.view
  weight: 100

```

I can now access the content defined by my controller at `node/1/reviews`, however when I go to `node/1` I don't see a reviews tab.

What am I doing wrong?

I've been using the following documentation so far:

# Answer
Your base route is wrong. You need to use the route that node uses for /node/1. That's not node.view. It's entity.node.canonical.
> 15 votes

---
Tags: 8, routes
---


# Question
Title: Display field collection items by using twig
I'm using the field collection module in Drupal 8 to encapsulate event informations so I've got a field collection with six sub fields (place, starting time, etc.).

In my twig template `field--field-event.html.twig`, I'd like to extract each item of the field collection and bring it separately to the view - but I can't figure it out. What's the right way to get the content of each field collection item and process it individually?

```
{% for item in items %}
  {{ kint(item) }}
{% endfor %}

```

Iterating through the field collection with above code gives me an impression that the field collection items have got a content (with `#markup`) and attributes but how do I get to the core/values of the field items?

# Answer
That is not a good idea to use kint() to collect the values somewhere in `#markup`keys or other render elements. You can get the values from the field object, which is in a field collection an entity which then refers to the children fields. But if you use field collection, you should try first to use the theming, that is provided by this module. That is configure the format of the field collection in ui and then look in twig debug for the templates that are used by doing this and modify them.
> 0 votes

---
Tags: theming, 8, entities
---


# Question
Title: Is there any way to count the number of items in cache?
In Drupal 6, I used to be able to look up the number of items via {cache\_MODULENAME} table direct in SQL. Is there any way to look it up via the cache API?

# Answer
> 4 votes
Given the interface provided for cache backends (`CacheBackendInterface`), you cannot.

It doesn't expose a method that returns the number of items in the case, which would have made things easier for your use case. There could be a cache backend with a method to count the number of items in the cache, but since it is not part of `CacheBackendInterface`, that would not be a method you find in every cache backend.
Since `CacheBackendInterface` doesn't expose any method to know the database table used for cache bins, you should assume some implementation details, and that those details are never changed. If you make assumptions about those implementation details, you can use a SQL query to count the number of items contained in a cache bin. Keep in mind that a cache backend could not use a database table at all, such as in the case of the `ApcuBackend` class.

---
Tags: 8, caching
---


# Question
Title: what is the hook name in order to alter theme function of specific element
imagine that we have a list if items in $items array that it's theme function is list\_item in specific page.

code is

```
theme('item_list', array('items' => $items));

```

but in my module, I want to alter the parameter 'item\_list' and I want to use my custom render function 'custom\_item\_list'

I know that I must register and define custom\_item\_list function but I don't know in what hook I am able to alter the theme\_function parameter of specific element.

# Answer
> 0 votes
You can use hook\_theme() function to use custom item list.

Hook theme:

```
function mymodule_theme($existing, $type, $theme, $path)
{
  if ($type == 'module')
  {
    return array(
      'custom_item_list' => array(
        'variables' => array('var_name'=>NULL),
        'template' => 'custom-item-list',
      ),
    );
  }
  return array(); //will raise fatal error if void
}

```

Call it as usual:

```
theme('custom_item_list', array('var_name' => mymodule_variable()));

```

# Answer
> 0 votes
You need to implement `hook_theme_registry_alter()` which is the hook modules can use to alter a theme function implemented by other modules. `hook_theme()` is for theme functions your module defines itself.

Just set `$theme_registry['item_list']['function']` to `'theme_custom_item_list'`, and `theme_custom_item_list()` will be called instead of `theme_item_list()`.
Keep in mind that, if you need to alter the content of the `$variables` parameter passed to a theme function, and not its output, you can implement `hook_preprocess_item_list()`, since every theme function has its own preprocess functions.

```
function mymodule_preprocess_item_list(&$variables) {
  // Change the title for the list.
  $variables['title'] = 'My own list title';
}

```

---
Tags: theming
---


title: Increase the panel pane title length

text:
# Question
Title: Increase the panel pane title length
There is a module for increasing the node title, but how to increase the maximum length of a panel pane title? I have a view pane which title must be overwritten in its panel pane settings. This works fine, but while appending extra tokens and styling to the title I bumped into the maximum length available. How can this be changed?

# Answer
> 0 votes
Do not put styling in pane title, move html/css in a template file, you can override next templates for that: panels-pane.tpl.php or views-view.tpl.php

---
Tags: views, panels
---


# Question
Title: Is it possible to put a single field of views in panels?
There is an existing views with a few fields output. I would like to put one of these fields in panels. Can I get it directly in Add Content of panels?

If it is impossible, what is the best way to put a single field in panels?

# Answer
Yes, you can add a single field directly from panels using **Add Content**, for this you may need to add a context with your entity.

* use **Arguments** option to pass an entity id from url argument and load dynamically context based on that entity;
* use **Context** option to manually specific a entity id to load its context;

You can check node view page as example, which has node context by default.
> 0 votes

---
Tags: views, panels
---


# Question
Title: How can I specify inner elements template in custom login page?
I am new in Drupal 8. I want to create a new theme to according to my HTML. What is the best practice to integrating a custom build theme to drupal engine.

I have covered all sections in Drupal 8 theming tutorial. Now I need to integrate custom login page.

I have added the following hook inside mytheme.theme file

```
function wms_aupl_theme(&$existing, $type, $theme, $path) {
  $hooks = array();
  $hooks['user_login_form'] = array(
      'render element' => 'form',
      'template' => 'user-login-form',
  );
  return $hooks;
}

```

And Inserted my HTML in user-login-form.html.twig file as follows.

```
<div class="col-xs-12">
    <div class="reg-form-2-wrap">
        <form{{ attributes.addClass('user-login') }}>
            <div class="row">
                <div class="col-xs-12">
                    <h1 class="main-head">Auktionsplattform</h1>
                </div>
            </div>
            <div class="row">
                <div class="col-xs-12">
                    <label class="gen-reg-label-small">Some dummy content</label>
                </div>
            </div>
            {{ form.name['#title'] }}
            <div class="row mrgn-top-30">
                <div class="row mrgn-top-30">
                    <div class="col-xs-3">
                        <label class="gen-reg-label">  </label>
                    </div>
                    <div class="col-xs-9">
                        {{ form.name. }}
                    </div>
                </div>
            </div>
            <div class="row">
                {{ form.pass }}
                <label class="gen-reg-label-pass"><a href="{{ base_url }}/user/password" class="reg-terms-anch">Passwort vergessen</a></label>
            </div>
            {{ form.form_build_id }}
            {{ form.form_id }}
            <div class="row mrgn-top-30">
                <div class="col-xs-12">
                    {{ form.actions }}
                </div>
            </div>
            <div class="row">
                <div class="col-xs-12">
                    <label class="gen-reg-label-small">Noch kein Konto? <a href="{{ base_url }}/user/register" class="reg-terms-anch">Hier registrieren</a></label>
                </div>
            </div>
        </form>
    </div>
</div>

```

Now i need to specify inner element's template. How can I specify inner elements template?

Is there any better way to do this?

# Answer
> 0 votes
See How to manipulate forms in Drupal 8:

> To make changes to the fields in your form, you have to change the specific twig templates. First check which twig templates correspond with the base theme of your Drupal application. It is important that you give new twig templates the same name as the original ones, otherwise your new templates will not be recognized.

---
Tags: theming, 8
---


# Question
Title: How do I move a group of nodes to another Drupal instance?
*What:* I'm breaking a part a *huge* D7 site into a D7 multi-site instance.

*Why:* Marketing demands have changed. They different units still want to use the same theme but have different main menus and slight CSS tweaks here and there. They also want separate authors and very different approval processes. This site is crippled under it's own weight.

*So far:* I've already copied over Content Types via Bundle Copy and most everything that will remain standard via source controlled features.

**How/Question**: How can I move a piece of content (node/XXX) to another Drupal 7 instance? A drush solution would be preferred so that I have the ability to script this across Stage and Production servers once we figure it out on Dev.

*Errata:* I've seen interesting methods to scrape content via feeds, sharing content, and seen great dev to prod workflows. However, I haven't seen something that addresses a one-time move of a node between instances.

# Answer
> 2 votes
For the scenario you describe, i.e. a once-off, one-way move from one site to another, automated with drush, Node Export is a good way to do it. You can use the `node_export_import()` function in your drush script or update hook:

```
  $file = 'exported_nodes.txt';
  if (file_exists($file)) {
    $nodes = file_get_contents($file);
    $status = node_export_import($nodes);
    // etc.
  }

```

# Answer
> 2 votes
What would suit you is the Deploy module: https://www.drupal.org/project/deploy

The README.txt states:

The Deploy module is used to deploy Drupal content to other Drupal sites or arbitrary systems. Two concrete use cases are:

* using it as a content staging solution
* **using it to push content downstream from a main site to several sub sites.**

Here's a demo: https://www.youtube.com/watch?v=7PjwT0HWHxw

---
Tags: 7, migrations, multi-sites
---


# Question
Title: Can I store a computed field as a field of a Content Type?
In content type = Person, I have these fields:
\- First Name \[node:field\_person\_first\_name\]
\- Middle Name \[node:field\_person\_middle\_name\]
\- Last Name \[node:field\_person\_last\_name\]
\- Suffix \[node:field\_person\_suffix\]

In views, I have successfully concatenated the full name by adding Global: Custom text and using Replacement Patterns to build the fields. However, this is time consuming.

These fields will always be put together in **both** of these two ways:
\- full name, last first
\- full name, first first

Is there a way that I can create two computed fields for these which I could store in the content type? If so, how do I do this? Note: I don't want to modify the original data.

**Update:**
I have Entity Token and Token already. I loaded Token Filter. I found, but have not yet loaded Token Field.

Token Field suggests that it might be nice if one could define a field "without needing to know any PHP" but the samples on this page indicate otherwise. My HTML knowledge is slight and PHP is non-existent.

I did follow a training video which gave me access to some tokens when creating a new field in Person, but these did **not** include tokens for fields within the Person content type.

Will this be possible (without PHP) if I install Token Field?

**Update 2:**
The site simplytest.me is excellent. Token Field loaded. Unfortunately in a real test, I'm getting "Cath \[node:field\_person\_middle\_name\] Staincliffe \[node:field\_person\_suffix\]" because author Cath Staincliffe doesn't have a middle name or suffix. Do you know how to instruct the module to only use a name if one exists?

# Answer
The Concat Field module looks like it can do what you want. From the README:

> This module provides a new field type that allows you to select other fields from that content type (or any bundle), and it will concatenate their display values into a single field on save.
>
> The example use case is then using the field as an exposed filter in a View.

Or you can write some code to do it via a custom module that calls the `hook_node_presave` function. In your content type definition, create the fields you want, and set their display type to Hidden. Then, in your function, set the values. See the answer to this question for more info:

How to use hook\_node\_presave to change field's value

**Edit:**

While it looks useful at first glance, the Concat Field module is very limited. You can't change the order of the fields, and it requires patches in order to generate any kind of output.

Another option would be to use the Token Field module. With this module, you can create a field into which you can enter tokens. This will give you a lot more flexibility - you can place the fields in whatever order you want, and specify punctuation or other characters around them.

**2nd edit to answer updated question**

> Token Field suggests that it might be nice if one could define a field "without needing to know any PHP" but the samples on this page indicate otherwise.

My interpretation of the Token Field page is you only need to know PHP if you want to use conditional tokens, and that's what the sample code illustrates.

> Will this be possible (without PHP) if I install Token Field?

In theory, yes, but the only way to know for sure is to try it. If you're worried about compromising your site or database, install Token Field on simplytest.me and set up your content type there.
> 2 votes

---
Tags: 7, entities, tokens
---


# Question
Title: How to adjust the length of [node:summary] for metatags?
How can I tweak the amount of characters for `[node:summary]`, so that the description metatag never shows more than 150 characters?

On admin/config/search/metatags/config/node I can only see for description token `[node:summary]`, which does not allow me to control the amount of characters that get displayed on the source code. I would need to trim it to max 150 characters, but I have no idea how/where this can be done.

# Answer
> 1 votes
You can do a few different things. Assuming you are using the metatag module.

1) Prevent metatags from saving with more than 150 chars using a presave hook:

```
function hook_metatag_presave(&$metatags, $entity_type, $entity_id, $revision_id, $langcode) {
  dsm($metatags);//debug what the array is. You can trim the values for the metatags here.
}

```

2) Alter the metatag before bing cached:

```
/**
 * Alter metatags before being cached.
 *
 * This hook is invoked prior to the meta tags for a given page are cached.
 *
 * @param array $output
 *   All of the meta tags to be output for this page in their raw format. This
 *   is a heavily nested array.
 * @param string $instance
 *   An identifier for the current page's page type, typically a combination
 *   of the entity name and bundle name, e.g. "node:story".
 * @param array $options
 *   All of the options used to generate the meta tags.
 */
function hook_metatag_metatags_view_alter(&$output, $instance, $options) {
  if (isset($output['description']['#attached']['drupal_add_html_head'][0][0]['#value'])) {
    $output['description']['#attached']['drupal_add_html_head'][0][0]['#value'] = truncate_utf8($output['description']['#attached']['drupal_add_html_head'][0][0]['#value'],150);
  }
}

```

---
Tags: meta-tags
---


title: Calendar module translation

text:
# Question
Title: Calendar module translation
I have installed the Calendar module and would like to translate a few fields:

At the above screenshot, I'm looking for the day strings ("Sun", "Mon", "Tue", Wed",...). I've been searching everywhere, but can't find where they are located.

Where can I find these strings so I can translate them in the language I prefer?

# Answer
Go to `Administration > Configuration > Regional and language > Translate interface` and search for `!day-abbreviation`. Then translate these strings to the language you prefer.
> 0 votes

---
Tags: 7, views, datetime
---


# Question
Title: Node Migrations with programmatic url aliases
**Can anyone advice me on how to programmatically create multiple url aliases for each row of a migration?**

I am using the Migrate module to migrate page content into Drupal from an XML document.

The existing system has multiple *url alias* data for each page and I need that same information represented in Drupal - which is proving to be challenging.

I tried doing the following in the **complete** function of my custom migrate class:

```
function complete($entity, $row) {
    // drush_print_r($entity);
    // Create an object with our redirect parameters
    $redirect = new stdClass();
    $redirect->source = "node/{$entity->nid}";     // From URL
    $redirect->source_options = array();
    $redirect->redirect = 'http://www.google.com';        // To URL
    $redirect->redirect_options = array();
    $redirect->status_code = 0;            // Redirect Status, 0 is default
    // $redirect->type = 'redirect';
    $redirect->language = LANGUAGE_NONE;
    // Create the redirect
    redirect_save($redirect);

 /****************** **I also tried the following** *******************/
    // $entity->path['alias'] = 'test/testing';
}

```

I then carryout a sample migration but my url redirects are not present in the node edit area.

Can anyone help, please?

# Answer
If I understand correctly, based on your example, you'll need to switch the to and from URLs. If you want the new node to display the redirects in the node edit form, the node ID should be as follows:

```
$redirect->redirect = 'node/' . $node->nid;

```

FYI - programmatic redirect creation here.
> 0 votes

---
Tags: 7, uri, migrations
---


# Question
Title: How to implement something like OG which the groups can manage on their own?
I'm building a learning tracking site for a community where Mentors will match up with Mentees. I'd like them to create either an organic group or a paired relationship to share content (seen only by the two of them plus a supervisor, observer, or instructor).

The catch is I'd like to let them do it on their own. In other words, I'd like to "get out of the way" and not maintain the actual groupings.

Does this sound like a job more for Organic groups (OG) or User Relationships? Is there another technique that could get the job done more smoothly?

And, how can they share content only amongst those with in that group or relationship?

If I use OG, how can I best let users create and invite others without my intervention?

# Answer
> 1 votes
You could, for sure, use the Group module for this. Group allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections. It is available as of D7, and has a D8 version also. It is designed to be an alternative to Organic Groups. The Group module creates groups as entities, making them fully fieldable, extensible and exportable.

For more details about how Group compares to Organic Groups, refer to my answer to "What are the features of the Group module versus Organic Group module?". And for more details about the various roles and permissions, refer to my answer to "What are the various roles supported by the Group module?".

# Resources

---
Tags: 7, organic-groups, users
---


title: Date popup on exposed filter

text:
# Question
Title: Date popup on exposed filter
How can I get a date popup on the exposed filters of a view on D8 ? I do not see the option, is it on D8 yet?

# Answer
> 3 votes
Currently, exposed filters in Views in Drupal 8 don't use the new HTML5 elements. Essentially, you get text inputs, selects, or checkboxes/radios.

There is an existing feature request to add this to Drupal 8.

I suspect you could form alter the exposed form to change the types. This is untested, but essentially what the patch on that issue does:

```
function MYMODULE_form_views_exposed_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  $form['the_exposed_date_element']['#type'] = 'date';
}

```

That won't work for ranges, but it should give you a start.

---
Tags: 8, views, datetime
---


title: Conditionally load PHP class

text:
# Question
Title: Conditionally load PHP class
I made 2 custom modules: boutique and paypal. paypal is a dependance of boutique.

I check if paypal is enabled, with the following code.

```
namespace Drupal\boutique\Form\Multistep;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\paypal\Controller\PaypalController;

abstract class MultistepFormBase extends FormBase {
  protected function saveData() {
    if (\Drupal::moduleHandler()->moduleExists('paypal')) {
      $test = new PaypalController();
      $test->setPaiement(10,0,1);
    }

    $this->deleteStore();
    drupal_set_message($this->t('The form has been saved.'));
  }

}

```

All is working good, but `use Drupal\paypal\Controller\PaypalController;` is always be here; if the paypal module is not present, does it create problems? How can I conditionally use use Drupal\paypal\Controller\PaypalController;\` only when the module is installed?

# Answer
> 3 votes
You don't have to prevent anything.

The use is just alias information. It doesn't care if the class that you're aliasing doesn't exist. As long as you don't actually use it, it won't fail.

---
Tags: 8
---


# Question
Title: Drupal 8 installation (bash) script. I want the latest stable v8 version each time. But how?
My Drupal 7 script utilised a make file which specified '7.x' as the Drupal version to install, drush make would fetch the correct core files.

My current Drupal 8 script uses git to clone and then checkout a version, eg. 8.1.0, and then renames the remotes as per the instructions on this page. However since this method downloads the entire Drupal project history, I end up with a huge project folder.

I work for an agency and we install Drupal for website projects, so our need is not for the latest dev builds, otherwise I image I would just use:

```
git clone --depth=1 [url to drupal.git]

```

I'm looking for a way to clone the latest stable (release) v8 branch, with no extra files. I could specify the zip on the release page, but this would mean updating the script upon each new release. I tried using Composer, but ended up with a much more complex than necessary folder structure.

Can someone help me with a way to get essentially a copy of the latest v8 .zip file via a script?

Thanks!

# Answer
As mradcliffe said in the comment, if you don't want to use composer (which I would really recommend you look into), you can simply use drush. You just need this:

```
drush dl drupal

```

This defaults to the latest stable Drupal 8 version. If you want to have a git clone (which is way slower), you can tell drush to do that too:

```
drush dl --package-handler=git_drupalorg drupal

```
> 1 votes

---
Tags: 8, installation, version-control, installation-profiles
---


# Question
Title: Where are all the controller classes instantiated?
In Drupal 8, if I want to create a form, I have to define a class inside the module folder like this.

```
class MyForm extends FormBase{

   public function getFormId()
   {
     return 'my_form';
   }
   public function buildForm(array $form, FormStateInterface $form_state)
   {

   }
   /* AND ALL OTHER OVERRIDDEN METHODS  */
}

```

Then I need to register a path for it in module.routing.yml.

```
module_name.myform:
  path: '/admin/structure/myform'
  defaults:
    _form: '\Drupal\my_formr\Form\MyForm'
    _title: 'My form'
  requirements:
    _permission: 'administer banner configuration'

```

Where is the `MyForm` class instantiated? What calls all the methods we are overriding?

We just define the class and register a path for it; neither we create an object of that class, nor we invoke any of the methods.

So, how does Drupal 8 manage these classes?

# Answer
So, first, this is not a controller, it's a form class. Controllers are instantiated by the routing component.

Every route must have a controller. \_form and some other special cases are processed after routes were collected and the actual controller is added. For forms, that is `\Drupal\Core\Controller\HtmlFormController`.

The actual processing happens in `\Drupal\Core\Controller\FormController::getContentResult()`, which calls `\Drupal\Core\Controller\HtmlFormController::getFormObject()`, which in turn uses `\Drupal\Core\DependencyInjection\ClassResolverInterface::getInstanceFromDefinition()` to instantiate the form class.

FormController then hands of the processing of the form to `\Drupal\Core\Form\FormBuilder`, which uses various other classes in the Form namespace.
> 5 votes

---
Tags: forms, 8
---


# Question
Title: Upgrading Drush 6 to Drush 9 on Centos 5 server
I haven't updated drush in awhile and looking to update it to the latest. I'm not exactly sure how it was installed originally. But when I do a **which drush**, it shows it resides in **/usr/bin/drush**

When I do a **drush dl drush** \- I only get the option to upgrade to 7.x only.

How can I update it to Drush 9?

Can I just do a git clone of the drush repo from: https://github.com/drush-ops/drush

Then do I just do a checkout of the drush 9 tag? But how do I make it the default drush application to run? Or do I just overwrite the file in /usr/bin/drush?

FYI: My linux server admin skills aren't up to par.

# Answer
> 3 votes
`drush dl drush` downloads the obsolete version of Drush from drupal.org. Drush was never intended to be used to download Drush via the pm-download command, even when it was hosted on drupal.org; the fact that this works is more of an anomaly or coincidence than design.

To update to a newer Drush, follow the usual instructions in the Drush documentation. Since you already have Drush in `usr/bin/drush`, use this location instead of the location stipulated in the docs (`usr/local/bin/drush`).

```
wget http://files.drush.org/drush.phar
chmod +x drush.phar
sudo mv drush.phar /usr/bin/drush

```

The Drush at files.drush.org/drush.phar is always the most recent stable version of Drush. To download a specific version, visit https://github.com/drush-ops/drush/releases. There is a phar available with every release of Drush from version 8 and later. You can, of course, replace your /usr/bin/drush at any time that you need to upgrade.

---
Tags: upgrading, drush
---


# Question
Title: Linux distribution suited for a clean and easy Drupal 8 install
I am experiencing a series of issues trying to prepare a server on my professional environment for running Drupal 8. By default, the IT team will install CentOS 6. More precisely, we are running CentOS 6.7.

The issue here is that the default versions of PHP and MySQL on that version of CentOS won't match the minimum required versions for running Drupal 8, which requires us to use repositories. As we are not Linux ninjas, we are facing several problems with the repos. I have two versions of libmysqlclient on the system, but the system will only 'see' the old one which doesn't support the MySQL version required by Drupal. The thing is really getting cumbersome.

So my next approach would be to suggest the IT team to go with the ideal Linux distribution which wouldn't require us to use the repositories, one that can deliver the cleanest install of PHP, Apache, MySQL, phpMyAdmin and Drush.

Based on your experience installing Drupal 8 on Linux servers, what is your preferred setup (Linux distribution), requiring minimum effort from server administrator, to install the appropriate versions of PHP, Apache, MySQL, phpMyAdmin and Drush that will work 'out of the box', discarding the use of custom repos? Thanks in advance.

# Answer
> 1 votes
Now that is released, Ubuntu 16.04 LTS with php 7.0, perfect for drupal 8.

---
Tags: 8
---


# Question
Title: How do I change the input type of an exposed filter in a view?
I have a view which lists products. I created an exposed filter based on price criteria.

The exposed filter shows a text input where you can type an integer number to get the products filtered. What I need is to replace the text input with a select list showing values such as 50000, 100000, 1500000, 200000.

I have the Better Exposed Filters module, and the Views PHP module enabled.

# Answer
> 0 votes
If you're using Better Exposed Filters, you can go to the edit page for the view (from /admin/structure/views). Then selected `Better Exposed Filters` for the `Exposed form style` which is under `EXPOSED FORM`.

Next click `BEF Settings`, scroll down to `Exposed Filter Settings`, and choose `Display "Price is higher than"` as `Select list`. If you don't have the option for select list, the Better Exposed Filters module won't be able to help you.

# Answer
> 1 votes
Edit View \>\> Configure filter criterion \>\> Select grouped filter (instead of the default, single filter) \>\> Set-up your options. That's it! you now have dropdown filters of free filled node field.

# Answer
> 0 votes
I came across the situation as well. As a quick "hack" you can do the following:

1. expose your filter as a text field, just like you show above
2. copy and paste the HTML output of that filter (everything between \< FORM ... and \< /FORM\> tags
3. add the HTML in the view's "header" as "global text area", make sure you select a text filter that allows FORM and SELECT tags
4. replace the \< INPUT ..\> tag with a \< SELECT\> tag (keep the name=... value the same)
5. add your \< OPTION\> tags, use value="" if you want an "Show all" option
6. hide the exposed filter by setting "exposed form in a block" to yes

Now you'll have a select list instead of an input box. You could probably add a bit of jquery magic if you want to preselect the option.

If you have a lot of options you could probably even use another view to generate the \< OPTION\> tags using rewrites. However, I haven't tried that one.

# Answer
> 0 votes
Use this module: Views Reference Filter

You create a separate view (or a new display of the same view) which returns the list of items to show in drop down select list of the exposed filter.

---
Tags: views
---


# Question
Title: How To Enter Data Into A Custom Drupal Entity?
I have a question regarding entering data into custom entities

I have a usage case I believe is better for Drupal Entities than Content Types and Nodes. I have installed Entity Construction Kit and used it to set up the structure for my entity.

What is not clear to me is how I go about getting data into my entity. I assume we could do a mass CSV import via Feeds. But what about making individual entries? I'm looking for a way to enter the data through the Drupal Administration forms (i.e. Add Content \> *Entity Name*) but that does not appear to be the case.

Are there additional modules out there that would give me the ability to do this?

Thank you for your time and assistance.

-- Chris

# Answer
I think everyone suffers the same bewilderment on first meeting ECK. Its workflow is bonkers.

You begin by creating an entity type and optionally renaming the default bundle (which otherwise will have the same name as your entity). I recommend giving the bundle a unique name to avoid confusion in this rabbit warren interface.

Then from the list of entities, click into that entity and then into the bundle. From here you can manage fields - and add your data from the 'entity list' tab. There, the link to add new instances of your entity type will be at the top of the interface - "+ add \[name of your bundle\]" and the list there will effectively serve as a rudimentary content list for that entity until you can whip something up in views.

If you want to cut through the labyrinth and use a simple link to add your data, it'll be structured like this:

admin/structure/entity-type/\[your entity name\]/\[your bundle name\]/add
> 1 votes

# Answer
Answering your original question I would like to propose Model Entity module for your consideration. It is less known than ECK, but in a few projects it gave enough support for my goals.

Out of the box you will have entity editing forms not under Structure but for a bit more appropriate place - Content, so URL will look as /admin/content/models/add .

Hope this helps!
> 0 votes

# Answer
I use Inline Entity Form on my Drupal site. Although it is not entirely clear from the linked page, this module has options that allow you to create new entities (of a specified type & bundle), and then remove them from the form, *but leave them in the database*, you may then select to add the entities for display in other forms. You can enable and disable entity creation on each instance of a form.

The rest of my setup includes:-

1. several custom entity types made with ECK, add fields using the usual UI.
2. On a node\[\*\] add an entity reference field for your custom entity, you should have two new choices for the widget - either a single entity form, or a multi-entity form.
3. The entity creation form is now shown as part of the node creation page - and so will be accessible to those who have the usual permissions.
4. Be sure to review the permissions for creation of the appropriate entity as well, otherwise the form will not function.

\[\*\]this does not have to be a node, I also use this setup on my User account page.
> 0 votes

# Answer
I'm new to Drupal, but had the same question. After poking around, it seems that the https://www.drupal.org/project/entityform module is useful for entering data into custom entity data fields in Drupal 7. In 8 this will be Eform.

I've installed Entityforms and it seems to work. I have not had enough time to run into problems yet, though. Good luck.
> 0 votes

---
Tags: entities
---


# Question
Title: Better Exposed filter when shown in pane configuration, then they are all coming as checked
Create a view of type Content Type, add a filter expose it, select it as drop down (Will be better if term reference field). After that select Exposed Form Style as Better Exposed Filters, and under BEF settings, show the filter as checkbox. After that under Pane Settings \>\> Allow Settings \>\> Check the checkbox "Use exposed widgets form as pane configuration", and save the view. After that create a mini panel through pane, and under settings you will see filters as checked.

Please give me some idea for the same.

# Answer
Issue was of BEF version, prev. version was 7.x-3.0beta3, after upgrading to 7.x-3.2, problem gets resolved.
> 0 votes

---
Tags: panels, views
---


# Question
Title: How do I theme a blog listing page for a specific taxonomy term?
I have a site, where a blog listing of a particular category, say Resources, has to have the "Read More" button say "Download Resource" instead.

I saw that this is controlled by a template file called 'node--blog-tpl.php' in the theme, with the following code:

```
    <?php if($extended == '1'): ?>
        <a class="btn readmore" href="<?php print $node_url; ?>"><?php print t('Read More');?></a>
    <?php endif; ?>

```

Since I wanted to change this just for the 'Resources' category, which was Taxonomy Term 23 for me, I copied this file and renamed it all manner of combinations/permutations of filenames with 'taxonomy--term-23' in it, but nothing seems to work.

Can someone please help me with this? I would be very grateful.

Thanks in advance, Jasper

# Answer
Blog list pages render node teasers. I think that the automatic template suggestion patterns would only operate on node attributes and taxonomy is not one.

You can add this to your theme's `template.php` file

```
function THEME_preprocess_node(&$variables) {
  // check for blog and teaser
  if ($variables['type'] == 'blog' && $variables['view_mode'] == "teaser") {
     // check for taxonomy term on node
     dpm($variables);
     if ($variables['field_TAXONOMYFIELD'][LANGUAGE_NONE][0]['tid'] == TAXONOMYID) {
       // change the readmore link here or add code for template file
       $variables['content']['links']['node']['#links']['node-readmore']['title'] = "Custom Read Me";
     }
  }
}

```

If you don't want to override the readmore link inside the preprocess function but absolutely want a template file, then you can instead do this:

```
array_unshift($variables['theme_hook_suggestions'], "node__blog__blahblah");

```
> 0 votes

---
Tags: theming
---


title: hook_block visibility

text:
# Question
Title: hook_block visibility
I have a custom module defining a block which needs some complex page visibility rules that I'll write later. In building out the basic `hook_block` code the `visibility` and `pages` settings don't seem to be working when returning `FALSE`.

```
function popup_footer_block($op = 'list', $delta = 0, $edit = array()) {
  if ($op == 'list') {
    $blocks[0] = array(
      'info' => t('Popup Footer'),
      'visibility' => 2,
      'pages' => popup_footer_block_visibility(),
    );

    return $blocks;
  }
  else if ($op == 'view') {
    switch ($delta) {
      case 0:
        $block = array('content' => 'foo bar');
        break;
    }

    return $block;
  }
}

function popup_footer_block_visibility() {
  return FALSE;
}

```

# Answer
> 0 votes
`'pages' => '<?php return popup_footer_block_visibility(); ?>'` worked. Disable the module, delete the module entry from the database, re-enable the module.

# Answer
> 0 votes
When the block visibility is set to 2, `$block[0]['pages']` needs to be a string that can be passed to `drupal_eval()` as first argument. In fact, the code which handles the block visibility is the following one.

```
  // Match path if necessary
  if ($block->pages) {
    if ($block->visibility < 2) {
      $path = drupal_get_path_alias($_GET['q']);
      // Compare with the internal and path alias (if any).
      $page_match = drupal_match_path($path, $block->pages);
      if ($path != $_GET['q']) {
        $page_match = $page_match || drupal_match_path($_GET['q'], $block->pages);
      }
      // When $block->visibility has a value of 0, the block is displayed on
      // all pages except those listed in $block->pages. When set to 1, it
      // is displayed only on those pages listed in $block->pages.
      $page_match = !($block->visibility xor $page_match);
    }
    else {
      $page_match = drupal_eval($block->pages);
    }
  }

```

---
Tags: 6, blocks
---


# Question
Title: Drupal View for the 10 Most Recent Items Sorted by Date ASC
Is it possible to construct a view of the 10 most recent nodes sorted by date in ascending order?

This sounds simple, but it seems as if it's more complicated than I'd imagined.

I think to do this in SQL you'd need a subquery, and I can't see that views is capable of that...

...or is it possible to reverse the order of the rows in the view after they're brought back from the database?

# Answer
It seems like a problem with sorting and offset.

To get the **10 most recent** nodes sorted by **date descending** is easy and will return the correct result. You are however sorting for the **10 most recent** by **date ascending** and will just get the **10 oldest** nodes.

Ideally you need to get the count of all nodes as by your criteria, then subtract 10 from that to use as the offset.

The easiest is to just **reverse the order before rendering**. Construct your view to sort by **date descending**, then add this to your theme's `template.php` file:

```
function THEME_views_pre_render(&$view) {
  if ($view->name == "VIEWNAME" && $view->current_display == "DISPLAYNAME") {
    $view->result = array_reverse($view->result);
  }
}

```

After you add this code you need to clear your cache.

You get the view machine name and display name like this:

Hover mouse on View tab, then look at link below: here `most_recent` is the view machine name and `page` is the display name.
> 3 votes

---
Tags: views
---


# Question
Title: Management of priorities with node_access
I do not understand how priorities are set for the node\_grants... I have a module node\_grants function that provides 4 grant ids for the user, but some nodes only have 2 gids... how do I know which one allows the user to view the node or not?

Thanks,

# Answer
If you install the Devel module, there is a sub-module called Devel Node Access (DNA) that you can also enabled.

When you do this, two new blocks will become available. One shows node access by users. The other shows the access records for the node you are viewing (or the nodes that happen to be on that page), both `hook_node_access()` and grants.

Typically, I will install both blocks at he bottom of the Content region, as they can be big/wide, and only give their view permission to a few users. If I am having grant weirdness, then I give the permission to all on a test site, and use user masquerading to see what is happening.

And as for priorities, this is described fairly well in the documentation on node access rights. In short:

* Deny by default
* Check for bypass access permission
* Call `hook_node_access()` per Drupal module ordering. First denier wins, then first allower wins.
* If there isn't a winner, `hook_node_grants()` is run per Drupal module ordering to build the list of grants. Then tirst denier wins, then first allower wins.
* Otherwise deny.

Try to read through `node_access()`, after the node access rights page, for the finer details.
> 2 votes

---
Tags: users
---


# Question
Title: Custom Entity - use taxonomy fields in views
I've created custom content entity, where one of fields defined in BaseFieldDefinitions() is

```
$fields['game_category'] = BaseFieldDefinition::create('entity_reference')
    ->setLabel(t('Game category'))
    ->setDescription(t('Game category'))
    ->setSetting('target_type', 'taxonomy_term')
    ->setRevisionable(false)
    ->setCardinality(-1);
;

```

Now, I'm trying to create a list using Views, where one of displayed fields will be "Game category" term name. What I managed to achieve is to display that term's tid.

QUESTION: How to display term's name ?

I suppose I should add a relationship, so Views is able to make a JOIN with taxonomy table

My class exposing fields to Views looks like this:

```
class GameViewsData extends EntityViewsData implements EntityViewsDataInterface  {

public function getViewsTableForEntityType(EntityTypeInterface $entity_type) {
    return $entity_type->getDataTable() ? : $entity_type->getBaseTable();
}

public function getViewsData() {

$data = parent::getViewsData();

$data['game'] = array();
$data['game']['table']['group'] = t('Game Entity Table');
$data['game']['table']['provider'] = 'game_entity';

$data['game']['table']['base'] = array(
    'field' => 'id',
    'title' => t('Game Entity Table'),
    'help' => t('Game Entity Table'),
    'weight' => -10,
);

$data['game']['name'] = array(
    'title' => t('name'),
    'help' => t('name'),
    'field' => array(
        'id' => 'standard',
    ),
    'sort' => array(
        'id' => 'standard',
    ),
    'filter' => array(
        'id' => 'string',
    ),
    'argument' => array(
        'id' => 'string',
    ),
);

$data['game_entity_game__game_category'] = array();
$data['game_entity_game__game_category']['table']['group'] = t('Game Entity Table');
$data['game_entity_game__game_category']['table']['provider'] = 'game_entity';

$data['game_entity_game__game_category']['table']['join'] = array(
    'game' => array(
        'left_field' => 'id',
        'field' => 'entity_id',
    ),
);

$data['game_entity_game__game_category']['game_category_target_id'] = array(
    'title' => t('game_category_target_id'),
    'help' => t('game_category_target_id'),
    'field' => array(
        'id' => 'standard',
    ),
    'sort' => array(
        'id' => 'standard',
    ),
    'filter' => array(
        'id' => 'string',
    ),
    'argument' => array(
        'id' => 'string',
    ),
);

return $data;
}

```

}

# Answer
You didn't say that you wanted to do this programmatically, so I'll give you the answer for doing it in the UI. Since you have defined the field game\_category as an entity\_reference, you can add a relationship in your view to Taxonomy. See Add a relationship to a view for an example.

Then, any field in Taxonomy will be available in your view, including the name. Since this is built into the Views UI by default, you do not need any of your getViewsData() custom code.
> 1 votes

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


title: Handle node save concurrency

text:
# Question
Title: Handle node save concurrency
## Introduction

I need to prevent node update when two or more users try to update node on almost same instance (simultaneously) and instead put the requests in a queue and process one by one.

## A live example

For node/1, if three users u1, u2, u3 try to update node, then only the user on the basis of "First Come First Serve" should be allowed to update the node(read & write) and others should wait in a Queue.

If users u1, u2, u3 request one by one, In this case when the node update by u1 is completed successfully(until then don't allow next request to read data), then only allow u2 to process(read & write), and similarly for u3 and so on.

Here read from u2 depends on final write by u1. One operation should be isolated.

Also the problem is with **node\_save()**. It takes much time when the traffic is more. Is there any way to boost it.

## System details:

> Drupal 7.22, 2013-04-03
>
> Mysql version: 5.1
>
> PHP : 5.3
>
> Apache: 2.4

# Answer
> 2 votes
There's a module called Content locking that covers your use case.

> **Block concurrent editing**: When a user is editing a node, any other user that attempts to edit the same node will be blocked from doing so, and notified that the content is already being edited.

You can also adjust when a lock will expire if an edit is abandoned.

---
Tags: 7, commerce
---


# Question
Title: How do I get a dashboard like the one drupal.org is using?
In search of making the dashboard for the user like drupal.org site I came to know there is a dashboard module in the drupal core. It is already enabled but I am not getting user interface like drupal.org site, not for admin and not for otehr users, How can I activate that so the user profile looks like what is on drupal.org site. I enabled the permission for user also. And where is the tab for the dashboard or how to enable it? Or am I missing something?

# Answer
> 4 votes
The dashboard on drupal.org is made using Homebox module.

> Homebox allows site administrators to create dashboards for their users, using blocks as widgets. Blocks in a Homebox page are resizeable, and reorderable by dragging.

---
Tags: 7, dashboard
---


# Question
Title: How can I update content automatically every X hours?
I have a content type that I want updated every five hours. When some nodes haven't been updated, the I'd like to alert a content admin with a warning message containing the list of nodes that have not been updated, e.g. :

> \[node:title\] has not been updated! please update

The nodes can also be displayed in a block

# Answer
> 1 votes
This can be completely driven by Views & Views System Message module.

You can create a block view for node content of type XXX that has an added **Filter Criteria** *Content: Updated date* with the **Operator** set to *Is less than or equal to* and the **Value type** set to an *An offset...* of "-5 hours" **Value**. That will get you a block view of content XXX that was edited more than 5 hours ago.

The last part, the alert message, can be added in the **Header** area by selecting the *Global: System message* type and setting the parameters to your liking. Once the block view is saved, you can add the block to whatever region you feel most appropriate.

---
Tags: rules
---


# Question
Title: How to open various files(image,video,txt) as pop-up on the current browser page instead of opening in separate page?
I have seen on several sites, particularly news sites, If we click on video, the video does not open in the separate page, instead small window in the middle of the screen pops-up and video does play there itself and you can close that and behind that your current page is as it is. Same way when we click the image icon on the stackexchange text form to upload the image, small windows open of drag and drop appears.

Hence is there possible in drupal 7, for images, videos, pdf, txt files, word files etc. which opens on the same screen as pop-up in front of current screen.

# Answer
> 2 votes
What you're describing is a modal window. There's a few modules out there for Drupal that create modal windows. The one that probably best fits your use case (media consumption) is Colorbox. Out of the box, it only handles images but there are a number of supporting modules that can handle other media files. See the Colorbox project page link for more information.

---
Tags: 7, javascript
---