# Question
Title: How might one get a conditional display of tooltip or popup message from a rewritten view field?
The issue concerns a View displaying a partial set of fields from a content type "video record," containing a collection of info about videos. One of those items is a Boolean (checked or not checked) indication of whether or not this video is allowed to be added to a user's shareable lists, generated by the module Flag Lists. If it IS shareable (Boolean was checked in full record) then the View displays a checkbox, allowing it to be added to a list. If it's NOT shareable (Boolean was unchecked) then we want to suppress the checkbox and display something else instead; currently that is just an "X" and that is working. Partial display of this here:

The "X" in the View field, a table cell, is the result of a View field rewrite plus display of the text "X" on the condition of "no results."

However we also want to have some form of tooltip/popup message, for hover on the "X," that explains why it's not allowed to be selected. Ideally, if this View field contains "X" then the tooltip would be active; otherwise it wouldn't. Here is a simulation of that:

This is currently working and the tooltip message is generated by the module "Tipsy." However that requires CSS selectors to associate it with the proper item. The only way we can see to use this is to manually add (to Tipsy config) a unique selector for each and every item in the list where this condition applies. Most problematic is that the selectors (as far as I have been able to understand) merely identify a position in the table – so if the table is resorted, they would get out-of-sync.

Can anyone suggest another path for getting to the desired result? That could be either a different way to get the tooltip/popup message that would only be active on the relevant table cell contents, OR maybe backing up farther and presenting the checkbox/no checkbox option a different way, depending on the full content page's condition of shareable/not shareable.

# Answer
You are actually on a good track - and you can use html in the no result text field. An easy solution to just attach the tooltip to the 'X's would be to add the needed info for tipsy there:

```
<a class="tipsy-tooltip" title="My tool tip" href="#">X</a>

```

In the Tipsy module settings you would need to add the appropriate selector in the form of: a.tipsy-tooltip. The selector does not need to be unique - you can use classes instead of ids. That way you can address multiple entries with just one selector.

Selectors are not linked to the position in the table, but rather identify a particular tag. In this case the element the 'a' tag which wraps around X. If the table gets resorted, the tooltip is still attached to the Xs.

---

**Edit 1**

The Problem might just be your selector: `a.views-field views-field-nothing`.

CSS classes are interpreted linearly and the order is important. In this case you are telling tipsy to look for a html element *views-field-nothing* which itself is nested unter a link `a` with the class views-field. If you look at the inspector though you will see that the actual mark-up is different and probably looks close to this one:

```
<td class="views-field views-field-nothing">
    <a class="tipsy-tooltip" title="My tool tip" href="#">X</a>
</td>

```

A link `a` nested in a element with the classes *views-field* and *views-field-nothing*. Tipsy can't convert the default tooltip to a tipsy tooltip because it doesn't find the link to start with.

The correct selector would look like this: `.views-field.views-field-nothing a` (The missing space between the first two classes is important, as are the dots before the names which indicate they are classes rather than html elements or ids. If you made a space between the first two, it would look for an a-tag nested in a element with the class *views-field-nothing* which itself is nested under the element with the class *views-field*.)

Since views-field is a class applied to all fields views outputs you can as well leave it out though and just write `.views-field-nothing a`

The Problem with `views-field-nothing` is that it applies to all views and not even just for fields where 'no result' applies - views also uses the same class for fields of the type custom text. To make sure you just target the links you want to turn into tooltips it is easier addressing them with a class on the link itself - e.g. with the `a.tipsy-tooltip` selector I suggested. It specifically looks for all links with the class *tipsy-tooltip* so tipsy can extracts their title attribute and uses it for its tooltip text.

You should also pick the 'HTML Attribute' option in this case (Source: 'HTML attribute', Selector: 'title'). The only time you really need to use the 'Child Element' option is when you want to use HTML in the tooltip as you can't do that with the former. With the 'HTML Attribute' option tipsy uses whatever you put as the links title as the tooltip text - no extra classes needed.
> 1 votes

---
Tags: views, entities, tooltips
---


# Question
Title: Render node fields and labels in node template
I'm familiar with the Drupal 8 theming API, including `hook_preprocess_HOOK()`, as well as all of the theme template suggestions available when Twig debug is enabled.

However, what I would love to be able to do is to control all of the individual fields and optional labels for a node, inside the node--tool--full.html.twig template. (My content type machine name is *tool*.)

I also know that I can simply leave out the call to `{{ content }}` in the Twig template and call fields individually like this.

```
{{content.body}}
{{content.field_application_purpose}}
{{content.field_application_uses}}

```

And of course, if I want complete control over a field, including rendered markup (for example, field\_application\_uses), I can create another template (field--node--field-application-uses--tool.html.twig) and then wrap the field and its label in any markup I'd like.

So far so good.

But how can I control all of this from within the node template, in this case node--tool--full.html.twig?

My node is translatable, including the field label.

What I'd like to do, instead of having to create field templates for every field on the node/content type/bundle, is something like this.

```
<article{{ attributes.addClass(classes) }}>
  ...
  <div class="application-purpose">
    <h3>{{ node.field-application_purpose.label}}</h3>
    <p>{{ node.field-application_purpose.value }}</p>
  </div>

  <div class="application-uses">
    <h3>{{ node.field_application_uses.label}}</h3>
    <p>{{ node.field_application_uses.value }}</p>
  </div>
  ...
</article>

```

The above template snippet works for the value, but not for the label, and I spent hours trying to work out where to get the label.

In field--node--field-application-uses--tool.html.twig, the label is available as a variable, but how can I retrieve this at the node template level?

I'd ideally like to keep all of the fields and their markup in a single template, the node template, as opposed to having to create a template for each field.

# Answer
The label is in the field definition, you have to add `fieldDefinition` before `label`:

```
{{ node.field_myfield.fieldDefinition.label }}

```

To explain this, node is the node object. Content is the render array of the fields, that are build as configured in the view mode. In node you find the raw values and definitions of all fields of the node. In content you only find those fields that are in included in the view mode and they are already formatted as configured in the view mode. You also find each of the fields as object in content, but you cannot be sure, that the field is there, because if someone later removes the field from the view mode, your code will get a null value.
> 7 votes

# Answer
I've created this module that lets you print the field label and field value individually: https://www.drupal.org/sandbox/sutharsan/2763183

`<strong>{{ content.field_name|field_label }}</strong>: {{ content.field_name|field_value }}`

Let me know if it is useful to you I will promote it to a full project.
> 3 votes

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


# Question
Title: all my edit button cannot work and got "Invalid form POST data" AJAX error
I don't know why all my edit button doesn't work since yesterday. In the log report, I got an AJAX HTTP error with 200 HTTP Code and "**Invalid form POST data**." message. And when I clicked any "edit" button, I received an Ajax error without any response Text:

Here are some buttons I found which don't work any more:

1. From Feed Import Setting (edit button doesn't work):
2. From Content type Adding (add existing product button doesn't work):

Does anyone have any idea why I got this???

# Answer
> 1 votes
An AJAX HTTP error occurred is very general error and it can be related to many things.

Based on your provided information we can say it's a core callback (`/system/ajax`) and the callback exists (Result code: 200).

The main problem is that it returns the empty response. This is most likely caused by WSOD (white screen of death) which can be related to:

* out of memory issue (increase `memory_limit` in your php.ini),
* timeout issue (increase `max_execution_time` in your php.ini),
* code issue (make sure you don't have any exit() or die() which terminates your code),
* cache issue (so please clear your cache, including memcached/redit if you're using it).

To debug this, you should:

1. Check your watchdog table for any errors (e.g. `drush ws --tail --full`).
2. Check your PHP error log for any PHP errors.
3. Use XDebug PHP extension, after configuring it enable `xdebug.auto_trace` parameter (only temporary), then reproduce the problem and check the trace file for more details.

---
Tags: 7, ajax, debugging
---


# Question
Title: View is using original template rather than new custom template
I have copied the views-view-grid.tpl.php file from the views module theme folder into my sites themes/my\_theme/templates folder and renamed it views-view-grid--panel-pane.tpl.php, as was suggested in the 'Theme: Information' tab. After a rescan and flushing of caches, the views-view-grid-panel-pane is bold in the tab, however, my changes are not reflected in the preview. Am I missing a step? I copy/pasted the file name, and triple check it, and it's bold, so I feel pretty confident that's not the issue.

Thank you

# Answer
> 1 votes
> After a rescan and flushing of caches, the views-view-grid-panel-pane is bold in the tab, **however, my changes are not reflected in the preview.**

The view's preview does not use template files from your custom theme. It uses the admin theme.

Thus, you can add the template files to your admin theme. The Drupal default admin theme is called "Seven".

Another option would be to just go directly to the view page url or where the view block gets displayed and just ignore your view preview.

---
Tags: views, theming
---


# Question
Title: Make custom textfield autocomplete compatible with slashes?
I have a form which uses a textfield with a custom autocomplete path and it works just as it should. However, I get some unexpected behavior when the title/search string contains a backslash (e.g. '10/07/2016 Meeting').

After some investigation I realized that Drupal seems to interpret those as 4 separate parameters with only the first (in this case 10) being passed to the autocomplete function. I'm not sure how I can prevent this behaviour as the passing of the string to the form is handled internally by Drupal via the `'#autocomplete_path'` on the textfield itself.

I checked how entity reference handled this, but it is using an entirely custom field and not the `'#autocomplete_path'` on a regular textfield and wasn't of much use to me.

However it would seem odd to me that the textfield autocomplete shouldn't be able to support search strings with slashes - I just can't find out how to hook into the Drupal form to encode the string somehow.

How can I make my autocomplete field compatible with slashes?

# Answer
Take a cue from the Drupal core's taxonomy autocomplete implementation and just recombine the arguments passed into callback function back into one string:

```
function taxonomy_autocomplete($field_name = '', $tags_typed = '') {

  // If the request has a '/' in the search text, then the menu system will have
  // split it into multiple arguments, recover the intended $tags_typed.
  $args = func_get_args();
  // Shift off the $field_name argument.
  array_shift($args);
  $tags_typed = implode('/', $args);

```
> 0 votes

---
Tags: forms, ajax, 7
---


# Question
Title: How to make sure the footer is always at the bottom?
As an important note I do NOT mean `position: fixed;`!!!

When the body is smaller and does not take the full height of the browser size, the footer just likes to chill in the middle of the page. If you look in the photo I shared you can see more clearly what I mean. I've tried things like `body{height: 100%;}` to no avail. Even attempted this: https://css-tricks.com/snippets/css/sticky-footer/ and it seemed to just break it more (especially on the front page where this isn't a problem. Is there possibly a way to make sure the body size is at least the size of the browser always?

# Answer
> 2 votes
By default, the content gets adjusted as per the content. Hence you can set the height of content-column to screen size in css. But only `#content-column { height: ---px; }` will not work as it will fix your screen to that px only, hence you can solve that issue using `min-height` as shown below. I have set this in my site and it is working perfect

`#content-column { min-height: 500px; }`

So, what happens the content column always remains at around 500px minimum, which is near to average screen size hence, visitor visit your site it looks like filled in entire screen and footer will be always at bottom. and if content is more it will be adjusted accordingly. And you can change px to whatever you want.

**UPDATE-1**

Now with above method, you can set the height which does not go below 500px, but what if the default screen size is more than that. Which had been discussed in following comments,

**You can use the Viewport units: vw, vh, vmin, vmax**

So, following code will solve the issue,

`#content-column {min-height: 100vh}`,

where the `1vh = 1% of the screen height`. hence 100vh will cover the entire screen. Now, if you have specified the % in the html {} or body {}, then you need to take that value as 100%.

e.g. `body {font-size: 87.5%;}` -\> In bartik or Adaptive theme,

so for this your code will be,

`#content-column {min-height: 87.5vh;}`

# Answer
> 2 votes
You can make use of the `calc()` expression, and use `min-height` instead of `height`. Say your footer height is 100px:

```
body{
  min-height : 100%;
  min-height: -moz-calc(100% - 100px); /* Firefox */
  min-height: -webkit-calc(100% - 100px); /* Chrome, Safari */
  min-height: calc(100% - 100px); /* IE9+ browsers */
}
footer{
  height: 100px;
}

```

Get more info about `calc()` here

---
Tags: 8
---


# Question
Title: entityQuery with multiple conditions on taxonomy terms returns no result
In my use-case I have an entity which has two fields that reference to unique vocabularies.

News: \- tag (entity reference) \- category (entity reference)

If I query on one of those reference I get results however when I query both (an AND filter) I get no results. I have triple-checked it by now and there are entities that contain both the tag and category I am querying.

Is this an user-error or a Drupal bug?

```
$query = \Drupal::entityQuery('node')
    ->condition('status', 1)
    ->condition('type', 'news')
;
$group = $query->andConditionGroup()
    ->condition('field_tag.entity.name', ['cars'], 'IN')
    ->condition('field_category.entity.name', ['sport'], 'IN')
;
$query->condition($group);
$nids = $query->execute();

```

EDIT: I have found a work-around by querying on the raw value instead of entity.value. This is a non-desirable situation though

```
$query = \Drupal::entityQuery('node')
    ->condition('status', 1)
    ->condition('type', 'news')
;
$group = $query->andConditionGroup()
    ->condition('field_tag.entity.name', ['cars'], 'IN')
    ->condition('field_category', [1], 'IN')
;
$query->condition($group);
$nids = $query->execute();

```

# Answer
> 8 votes
The reason you can't do that is that both of these fields are entity reference to the same entity. That means that the base table is the same base table.

You are asking Drupal to Join the taxonomy\_data table to the node table and then make an impossible AND condition on it.

### P.S.

You can use `condition('field_tags', 1);` instead of `condition('field_tags', [1], 'IN');`

And as mentioned in the comments, the AND condition group is the default, so you don't need to specify it.

### P.P.S.

You should have both conditions use the referenced id to be consistent.

# Answer
> 1 votes
Actually I found a hack to this. here's my explanation of what I've found:

I had 3 fields in my content type each holding a reference to a taxonomy term from different vocabularies. And I wanted to query the entities for the ones that have a specific taxonomy term in each of those 3 fields (an and condition).

checking the internal SQL query that is produced after several attempts with different combinations of conditions I found that

```
[Previous conditions] AND (taxonomy_term__[taxonomy_term_field_name] IN  (:db_condition_placeholder_2)) AND (taxonomy_term__[taxonomy_term_field_name] IN  (:db_condition_placeholder_3)) AND (taxonomy_term__[taxonomy_term_field_name] IN  (:db_condition_placeholder_4))

```

basically as you can see, it has no reference to the actual individual fields using that specific vocabulary, so my hack is to do something like this:

```
 $query = \Drupal::entityQuery('node')
            ->condition('status', '1')
            ->condition('type', $content_type_machine_name)
            ->condition('field_holding_term_ref.entity.name', array($label_of_term_in_field1, $label_of_term_in_field2, $label_of_term_in_field3), 'IN');

```

again this works, I've tested it and it works as an AND condition returning only content type with those 3 taxonomy terms even if the references to those taxonomy terms are stored in different fields in the content type.

I'm not proud of the hack but it works, so if this can help somebody save sometime, go for it.

---
Tags: 8, entities
---


# Question
Title: Defining functions in a module and calling them from a controller
I want to use a function in both a controller and a module. where should I define that function?

Can I call a function in module from a controller? How I can do that?

# Answer
This is exactly the case when you define a Service:

* In your controller you call the service with Dependency injection
* In your module you call the static \Drupal::service('..')
> 2 votes

# Answer
First off, a controller is just an instance of a class. As such, calling a function from a controller is not different from what you would do in another PHP class. To answer your questions:

* *Where should I define that function?* You can define it in the module file, since that is already loaded when a controller object is created and its methods are called.
* *Can I call a function in module from a controller? How I can do that?* Yes, you can, and you don't need to do something more than calling the function as you would call it from another function, since modules are already loaded when a controller object is created.

Comparing a single function with a service doesn't make much sense; you will never replace a function like `taxonomy_get_title()` with a service. I would rather compare a service with a group of related function, and in that case, I would say that a service is preferable to a group of related functions.
> 1 votes

---
Tags: 8, page-controller
---


# Question
Title: Images are uploaded but those are not avaliable in a form
I have a problem with webform module and that too with my site only :( When I add form field with image upload, photos are uploaded but when I check submissions there are empty places, only I can find this photo in FTP in path sites/all/webform/

When I add required field, so user can not go to the next page break I choose file, format and weight is correct, I click upload a file, looks that is uploaded

I try to go to the next page break but it is impossible because appears a notice that this field is required and is empty...

I try to do in another webform created, without page breaks and another fields, but issue is the same.

In another drupal site in my server I don't have this issue. If you want to reproduce please go to my site: vidicon.nazwa.pl/brodnica/zgloszenie\_firmy

please fill fields with\* and after upload photo in last field and try to go to next step. It will be not possible but I will have this image on my server in /sites/default/files/webform/...

BTW I try to create a another simple form with image upload field and the same issue occurs, permission I set the same as in other site where webform works properly. I don't have any ideas, but I need this webform to my site :(

Thank you in advance for help.

# Answer
> 2 votes
Case is resolved, issue appears in drupal 7.43 and 7.44, I last version - 7.50 works ok

---
Tags: webforms
---


# Question
Title: Why does hook_menu() not show my items in menu?
Here's my code and I can't get why `hook_menu` doesn't work. My block menu doesn't showing in menu. As I understood this code (hook\_menu()) should show link in which for will work drupal\_post\_form using function instance\_export\_form.

So I mean that when I follow admin/config/content/instances\_export I get just content menu list, not a form which I need

```
    <?php

function instances_export_block_info()
{
    $blocks['instances_export'] = array(
        'info'  => t('Instance export'),
        'cache' => DRUPAL_CACHE_PER_ROLE,
    );

    return $blocks;
}

function instance_export_menu()
{
    $items = array();

    $items['admin/config/content/instance_export/settings'] = array(
        'access arguments' => array('administer site configuration'),
        'title'            => 'Configure export',
        'description'      => 'Chose what you want to export and where',
        'page callback'    => 'drupal_get_form',
    );

    $items['admin/config/content/instances_export'] = array(
        'title'            => 'Form to export data',
        'page callback'    => 'drupal_post_form',
        'page arguments'   => array('instance_export_form'),
        'access arguments' => array('administer site configuration'),
    );

    return $items;
}

```

Here info file

```
 name = Instance export and import module
    description = Allow to export synchronize few instance of Drupal
    core = 7.x
    version = «7.x-1.0»
    configure = admin/config/content/instances_export
    files[]=instance_export.module

```

# Answer
There are a few things that look out of place there:

1. Your module name is instance\_export so you should not use instance\_export\_form as a function name because Drupal will think that you are defining hook\_form() and you will run into problems. Best to use function names that are less likely to clash with other modules.
2. The menu item `admin/config/content/instance_export/settings` is using drupal\_get\_form() as the callback but isn't passing in any form ID as `'page arguments'`
3. The menu item `admin/config/content/instances_export` uses the page callback drupal\_post\_form(), which is not a Drupal function. I assume you want drupal\_get\_form() here also.

Something like this should work better:

```
function instance_export_menu() {
  $items = array();

  $items['admin/config/content/instance_export/settings'] = array(
    'title'            => 'Configure export',
    'description'      => 'Chose what you want to export and where',
    'page callback'    => 'drupal_get_form',
    'page arguments'   => array('instance_export_settings_form'),
    'access arguments' => array('administer site configuration'),
  );

  $items['admin/config/content/instances_export'] = array(
    'title'            => 'Form to export data',
    'page callback'    => 'drupal_get_form',
    'page arguments'   => array('instance_export_export_form'),
    'access arguments' => array('administer site configuration'),
  );

  return $items;
}

```

Note that I made up a form function for the first menu item (instance\_export\_settings\_form) and changes the one for the second menu item (instance\_export\_export\_form). This would be whatever you want your functions to be.

Also, if you want these pages to be tabs in your module's admin area do it like this instead:

```
function instance_export_menu() {
  $items = array();

  $items['admin/config/content/instance_export'] = array(
    'title'            => 'Configure export',
    'description'      => 'Chose what you want to export and where',
    'page callback'    => 'drupal_get_form',
    'page arguments'   => array('instance_export_settings_form'),
    'access arguments' => array('administer site configuration'),
  );

  $items['admin/config/content/instance_export/settings'] = array(
    'title'            => 'Configure export',
    'type'             => MENU_DEFAULT_LOCAL_TASK,
  );

  $items['admin/config/content/instances_export/export'] = array(
    'title'            => 'Form to export data',
    'page callback'    => 'drupal_get_form',
    'page arguments'   => array('instance_export_export_form'),
    'access arguments' => array('administer site configuration'),
    'type'             => MENU_LOCAL_TASK,
  );

  return $items;
}

```

I'm assuming that your hook\_block\_info() is not relevant to this question.
> 1 votes

---
Tags: routes, hooks
---


# Question
Title: I Can't add node of a custom content type
I have to add a new content type to my site for a new feature i'm asked. I already added two of them before (very early in the building of the site, in fact) and it worked well but this time, when i want to add a new node, my new content type doesn't appear in the list of content types (node/add).

It appears in the admin/structure/types page but not in the node/add.

I cleared the cache and rebuild permissions but nothing happened.

I also tried to create a very basic new content type but it didn't appear either.

An earlier exchange on this forum showed it wasn't likely to be the taxonomy access control module.

If I do a clean install of drupal and create a new content type, it works but on my site, i can't do it so i don't think it is because i forgot some step.

May it be because of some problem with a third party module ?

I don't think i have installed very exotic ones but i have some (CKEditor, Taxonomy access control, Piwik Web Analytics... )

I'm turning mad so if someone has some clue, it may really help.

Thank you

# Answer
After following clues mentioned in the above comments (by CodeNext), I was able to solve my problem. The issues and the solution I have compiled as below.

There were two problems.

* For some needed reason, I displaced the "add content" menu from "Navigation" to "Redaction" (a new menu). This caused the new content type not appear in the "Add content" page. By displacing the new content type in the "add content" menu, I could see my new content type in the right place.
* I had a underscore in the content type machine name. Because of this, i couldn't navigate to the node/add/newcontenttype page (I reached the node/add page). By removing it (the underscore), everything goes now the right way.
> 0 votes

---
Tags: nodes
---


# Question
Title: Passing arguments with special characters
I want to pass a token into my custom module via the URL, like so:

http://example.com/myurl?token=ffjei4T93F/ggF0PImZxlDWSR8JYHaPmkkjLSUVSKkr

Drupal has issues with passing tokens using clean URLs:

https://www.drupal.org/node/118072

...and because my token has a '/' forward slash in it it breaks if I use arg(1) to get the token.

What to do?

# Answer
> 2 votes
For Drupal 7, use `drupal_get_query_parameters()`.

https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal\_get\_query\_parameters/7.x

---
Tags: 7
---


# Question
Title: Delete all nodes where the taxonomy term matches a given value
I have a content type (example\_content\_type) with 3 3 fields: title, body, and pks\_type. pks\_type is a taxonomy term select list field. and 'pks\_type'has 2 terms:

* Type1, tid = 1
* Type2, tid = 2

I have 150 nodes using those taxonomy terms. Now I need to delete all nodes from 'example\_content\_type' except last 5 nodes, where the taxonomy term ID is 1.

How can I achieve this with `db_delete()`?

# Answer
I would suggest using EntityFieldQuery as it allows you to pick exactly the nodes you want based on a wide range of criterias (check the documentation here and a tutorial here) and you can exclude the last 5 nodes by adjusting the range of the query itself.

```
$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'node')
      ->propertyCondition('bundle', 'example_content_type')
      ->fieldCondition('field_pks_type', 'tid', '1')
      ->propertyOrderBy('created', 'DESC')
      ->range(5);

$result = $query->execute();

if (isset($result['node'])) {
  $nids = array_keys($result['node']);
  node_delete_multiple($nids);
}

```

In this case the query will find all entities of type *node* and bundle *example\_content\_type*, with the *pks\_type tid 1* and retrieve them newest first starting with the 6th entry (and thus ignoring the 5 last/most recently entered nodes).

*(I added the code for deleting the nodes, though it might be good to print a list of nodes to be deleted or back up the db before actually using the code.)*

---

**Edit 1:**

Just now saw you asked about using `db_delete()`. In this case you can still use the code above to retrieve the ids of the nodes you need to delete and delete them with `db_delete()` rather than `node_delete_multiple()` \- however unless you have a specific use case where you need to use `db_delete()` it is better using the appropriate delete hooks as those will also clear corresponding field tables and allow other modules to react to the node's deletion.

```
if (isset($result['node'])) {
    $nids = array_keys($result['node']);

    foreach($nids as $nid) {
        db_delete('node')
        ->condition('nid', $nid)
        ->execute();
    }
}

```
> 0 votes

# Answer
The major problem here is the "except last 5" constraint. I suggest the following solution:

db\_select the nodes' nids that you don't want to delete in the first step, like

`$savenids = select nid from node where -whatever- limit 5`.

Then db\_delete the rest of the nodes like

`delete from node where -whatever- and nid not in $savenids`.

The -whatever- terms strongly depend on your field setup, take a look at your tables for that.
> 0 votes

---
Tags: 7, database
---


# Question
Title: The EU Cookie Compliance module doesn't display the message
I just downloaded the EU Cookie Compilance module 8.x-1.0-beta4 and the legal message doesn't show in my page.

First, I configured the module, and then set the *Display EU Cookie Compliance popup* permission for the anonymous user, but the message doesn't appear.

Why? What do I need to do to make it appear?

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

# Answer
> 0 votes
As a workaround, setting the variable *$geoip\_match* to *true* (line 57 of file *eu\_cookie\_compliance.module*) makes the pop up appear:

```
$geoip_match = true;

```

I opened an issue in the module's page:

https://www.drupal.org/node/2763441

---
Tags: 8, cookies
---


# Question
Title: How is the module Userpoints Donation intended to work?
I enabled the Userpoints Donation module (part of Userpoints Contrib). Then I put a check in the settings for the type of material - (Choose which content types should show a donate points link).

What's next? Nothing has changed. It says "Only the checked content types will show a donate points link". But no reference appeared.

# Answer
> 0 votes
The purpose of the Userpoints Donation module is mentioned near the top of the module's source:

> ... uses User Points API to give users ability to give points to users.

But "*give*" actually means "*transfer*", as shown in `userpoints_donation_giveform_submit()`, which:

* increments the amount of points for the user who receives the donation (= **receiver**).
* reduces the same amount of points for the user who donates them(= **donator**).

Before actually doing so, various extra validations are performed, such as:

* Does the donator have sufficient points, so that after transferring the points the user points balance of the donator is still positive?).
* The receiver has to be a valid user.
* You cannot transfer points to yourself.
* The amount of points donated cannot be below 1 user point (which also implies that the donator can only "*give*" points, not "*take*" points ...).
* ...

However, for an appropriate link (with title "*Donate points to this user*") to be shown to the user who wants to do such donation, it is required that such user has been granted the permission "***give points to another user***". So if "*Nothing has changed*" (as in your question), it could well be that the required permission has not been granted yet.

---
Tags: 7, userpoints
---


# Question
Title: How can I view the IP addresses of visitors who view the home page of my site?
I need to gather the IP addresses of visitors who view the home page of the site. There are bots that bounce off of the home page thousands of times a day. The Statistics module makes the site too slow. I also tried the Visitors module which worked pretty well, but there was no way to reduce the results only for the home page. Is there an another way to exclusively view IP addresses that visit the home page?

**Edit:** A way that doesn't slow the site down with a lot of database writing.

# Answer
**Update:** For this project I ended up using the ip\_address() function from Drupal's core to get the ip address. I then created a small table with some restrictions to prevent too much data from being written.

```
<?php

/**
 * Implements hook_init()
 */
function MY_MODULE_init() {
if(drupal_is_front_page() && user_is_anonymous() && ip_address() !== 'our ip address') {
    $ip = ip_address();
    $ipdate  = time();

    $insert = db_insert('mytable')->fields(array(
            'ip_address' => $ip,
            'ip_date' => $ipdate,
        ))->execute();
    }
}

function MY_MODULE_menu() {
  $items = array();
  $items['view-results'] = array(
    'title'           => 'View List of IP Addresses',
    'page callback'   => 'MY_MODULE_fetch_results',
    'access callback' => 'user_is_logged_in',
    'type'            => MENU_CALLBACK,
  );
  return $items;
}

function MY_MODULE_fetch_results() {
$result = db_query("SELECT ip_address AS IPADDRESS, ip_date
                    AS IPDATE
                    FROM mytable
                    ORDER BY IPDATE DESC");
print "<title>List of IP Addresses</title>";
print "<h3 style='font-family:verdana, arial'>List of IP Addresses and Dates for Anonymous Users Home Page Visits</h3>";
print "<p style='font-family:verdana, arial; font-size:11px'>Hint: use CTRL + F to find</p>";
print "<div style='font-weight:bold; height:18px; background-color:#f5f1ec; font-family:verdana, arial'>
   <div style='width:45%; float:left;'>Ip Address</div>
    <div style='width:45%; float:left;'>Date of Visit</div>";
  foreach($result as $data) {
      print "<div style='font-weight:normal; background-color:#efefef; font-family:verdana, arial; height:18px; margin:4px;font-size:11px'>";
       print"<div style='width:45%; float:left;'>". $data->IPADDRESS . "</div>";
       printf("<div style='width:45%%; float:left; color:#336699;'>%s</div></div><div style='clear:both;'></div>", format_date($data->IPDATE, 'custom', 'j F Y g:i A'));
  }
drupal_exit();
}

```
> 0 votes

# Answer
Here are the three variables you need :

```
$client  = $_SERVER['HTTP_CLIENT_IP'];
$forward = $_SERVER['HTTP_X_FORWARDED_FOR'];
$remote  = $_SERVER['REMOTE_ADDR'];

```
> 0 votes

# Answer
If you are using Apache, all page requests are recorded in the log directory. On a Ubuntu machine the location of this directory will be `/var/log/apache2`.

To block spam traffic, I recommend the mod\_spamhaus module. This link contains information on how to setup mod\_spamhaus on a Ubuntu machine. The module checks for blacklisted IPs listed on the Spamhaus project and subsequently refuses the connection if a positive match is found.
> 0 votes

# Answer
1. Enable Drupals built-in **Database logging** module. To view the log, navigate to the Recent log messages page (http://example.com/admin/reports/dblog). However, I don’t see any reason why you should fill up your Drupal database with thousands of log entries, thus
2. Use a graphical analytics Tool like Piwik or GoogleAnalytics
3. Enable logging in your Apache (/var/log/apache2) or nginx Webserver. Additionally to analyze your log files more easily you can use
4. Awstats or Report Magic
> 0 votes

---
Tags: users, nodes
---


# Question
Title: How to transfer Userpoints between users?
I installed the User Points module (v7.x-1.0) and after going through all of the configuration I cannot seem to find the option for transferring Points between users.

Can someone point out how I find/activate this feature?

# Answer
Module Userpoints Donation has to be used.
> 0 votes

# Answer
There are basically 2 approaches you can choose from, as further detailed below.

# User points donations

Use the Userpoints Donation module, which is a submodule included in the (D7 version of the) Userpoints Contrib module.

If you use/enable it, make sure to also grant the required permission related to it (and to avoid asking yourself "How is the module Userpoints Donation intended to work?" ...).

# Rules

Use the integration between the User Points module and the Rules module to "roll your own cookies", by writing some custom rules to transfer user points from one account to another. As a sample, have a look at this rule, which is used in combination with voting of a node, whereas the author looses "-2" points, and the voter looses "-1" points:

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

```

If you simply adapt the amount of points (-2 and -1) to something like (eg) +25 and -25, you've a prototype to transfer (25) user points from one user to another. If you replace the Rules event by an event like "something is flagged" (created with the Flag module), a simple click could be used to indicate "I want to transfer 25 user points of mine to this user).
> 0 votes

---
Tags: 7, userpoints
---


# Question
Title: Content from the same content type as the current user
I have users with a "field\_org" entity reference (multiple values allowed) to the "Org" content type. I also have a "field\_org" (single value) in my "Article" content type.

When looking at a user profile (let's call this user "UserA"), how do I build a view that gets you "articles from your orgs" (i.e. created by other users that also belong to any of UserA's orgs)? And, bonus question: how do I exclude articles created by UserA? (since I have a separate "your articles" view showing in the same page).

I know this is probably a combination of relationships and contextual filters, but I can't figure out exactly how to configure them. Probably something like this:

* Contextual filter on node author to prevent "UserA's articles" from showing (set to "exclude" in the options)
* Contextual filter on node author, but probably set to one of the relationships below.
* Relationship between article nodes and orgs?
* Relationship between orgs and users?

Both contextual filters would load the same user ID using "Provide default value".

# Answer
1. Create a content view
2. Add the `Content: Author` relationship
3. Add the `Content: Author uid` contenxtual filter
    * Provide default value: `User ID from URL`

So far we have a view displaying content created by a certain user, we still have to narrow down the results to a single content type.

4. Add the `Content: Type filter = Org`

Note that a `page` view (with a path) will show no results if you just hit the path. To have results you must pass a `uid` to the url, like `mypath/%uid`. On the other hand you can create a block or a content pane and place/embedded it to the user's profile, view's will return all results (if any) for you!
> 0 votes

---
Tags: views
---


# Question
Title: Route logged in user to profile on all request to <front> node
I'm attempting to make a simple login page on the front page that once you log in it will route you to your profile. This part I got working with Rules, but if the user clicks the home link on the site at any point, when logged in, I want to route the user to the profile, not the front page.

I tried a similar trigger to the one I got routing a user when they log in. This being on page view trigger *when role is not anonymous* and URL alias is `/node` route to `user/[account:uid]`

When logged in I click the home button and it's not getting triggered. It just sends me to the homepage.

How can I do this with Rules?

# Answer
It sounds like there's some missing detail (e.g. checking the right alias, token data not available, etc.).

A simple way to do this to do a page redirect action on a *Drupal is initializing* event with conditions, *Data comparison* on `[site:current-page:path]` & negated *User has role(s)* on `[site:current-user]`. Then you can check for the Drupal path that's set for your front page (i.e. '/node').

For example:

```
{ "rules_login_frontpage_redirect" : {
    "LABEL" : "Logged in Frontpage Redirect to Profile Page",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "NOT user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "1" : "1" } }
        }
      },
      { "data_is" : { "data" : [ "site:current-page:path" ], "value" : "node" } }
    ],
    "DO" : [ { "redirect" : { "url" : "user\/[site:current-user:uid]" } } ]
  }
}

```
> 1 votes

---
Tags: 7, routes, rules
---


# Question
Title: Hide taxonomy term in specific node form
I have a select list of taxonomy terms, all terms are needed for searching in views, but I don't need for insert new content. I wrote a custom module, which Hook should I use to hide some terms of my select list?

# Answer
Use hook\_form\_FORM\_ID\_alter

```
/**
 * Implements hook_form_FORM_ID_alter.
 */
function my_module_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
  $vocabulary_machine_name = 'my_vocabulary'; // Makes the search faster.
  $term_names = array(
    'Term 1',
    'Term 2',
    'Term 3',
  );

  foreach ($term_names as $term_name) {
    $term = taxonomy_get_term_by_name($term_name, $vocabulary_machine_name);
    unset($form['my_field']['#options'][array_pop($term)->tid]);
  }
}

```
> 0 votes

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


# Question
Title: How can I add some style to title of side bar block?
I want to add some style to my drupal 8 Sidebar menu, I want to create something like below image with **Font awesome** and css:

# Answer
You can do this thing entirely using the `CSS` and `FontAwesome` module, I have just tried in my trial site and posting the image of block title as below, I guess you are looking for the same.

The CSS code I have used is as below,

```
#block-yourblockID {
    .block-title {
      font-size: 20px;
      margin: 0 0 0 0;
      padding: 0 0 0 70px !important;
      background: #0166c3;
      color: #fff;
      }

  .block-title:after {
     font-family: FontAwesome;
     content: "\f100";
     float: right;
     background: #0156a2;
     padding: 0 5px 0 5px;
     color: #fff;
     } }

```

Now, for your title and its content you can adjust padding and margin for your fit. Also you can adjust the padding and margin of block to fit the entire title same as block width.
> 2 votes

# Answer
1. First add `position: relative` as a style to the containing element (most likely the `nav` element.
2. Add a pseudo element after the `h2` element, which you probably want to have your specificity include the class of the nav element.
3. Style the pseudo element with `position: absolute; right: 0;`
4. Tweak the styles of the `h2` and `h2:after` blocks to suit your needs.
> 2 votes

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


# Question
Title: Render a custom form in a custom template
For my site, I have to create a custom form in a custom template. It is not in a custom block, but in a custom tpl-file. I have searched the internet for a solution, but or the form is not shown or the fields are shown, but not in a \< form \> tag. This way, the submit-button does not work. When I render the fields in a self-written form-tag, the validate function and submit-function don't work.

Can someone help me?

**TPL-File**

```
$form = _odisee_forms($form, $dag, $datum, $uur, $campussen);
$form['infodag'] = form_process_checkboxes($form['infodag']);
$formulier = drupal_get_form('infodagen-block-form');
print '<form id="'.$formulier['#id'].'" accept-charset="UTF-8" method="'.$formulier['#method'].'" action="'.$formulier['#action'].'">';
print drupal_render_children($form);
//print render($form);
print render($formulier['form_id']);
print render($formulier['form_build_id']);
print render($formulier['form_token']);
print '</form>';

```

**forms.inc**

```
function _odisee_forms($type, $dag, $datum, $uur, $campussen) {
  $form = array();
  foreach ($campussen as $key => $campus) {
  $infomoment[] = t($dag[$key])." ".$datum[$key]. " @ " .$campus. " om ".$uur[$key];
  }
  $form['#id'] = 'infodagen-block-form';
  $form['infodag'] = array(
    '#type' => 'checkboxes',
    '#options' => $infomoment,
    '#required' => TRUE,
  );
  $form['voornaam'] = array(
    '#type'  => 'textfield',
    '#title' => t('<img src="/sites/all/modules/custom/odisee_forms/images/icon.png" class="icon">'),
    '#size'  => 15,
    '#attributes' => array(
      'placeholder' => array('Voornaam'),
      'class' => array('breed')
    ),
    '#required' => TRUE,
  );
  $form['naam'] = array(
    '#type'  => 'textfield',
    '#title' => t('<img src="/sites/all/modules/custom/odisee_forms/images/icon.png" class="icon">'),
    '#size'  => 15,
    '#attributes' => array(
      'placeholder' => array('Naam'),
      'class' => array('breed')
    ),
    '#required' => TRUE,
  );
  $form['emailadres'] = array(
    '#type' => 'textfield',
    '#title' => t('<img src="/sites/all/modules/custom/odisee_forms/images/arroba-symbol.png" class="icon">'),
    '#size' => 20,
    '#maxlength' => 128,
    '#required' => TRUE,
    '#attributes' => array(
      'placeholder' => array('E-mailadres'),
      'class' => array('breed')
    ),
  );
  $form['submit'] = array(
    '#type'  => 'submit',
    '#value' => t('Schrijf in!'),
    '#attributes' => array('class' => array('button')),
    '#submit' => array('_odisee_form_submit'),
    '#validate' => array('_odisee_form_validate'),
  );
  return $form;
}

function _odisee_forms_validate($form_id, &$form, &$form_state) {
  dpm($form_state, "state");
  dpm($form);
}

function _odisee_forms_submit($form, &$form_state) {
}

```

# Answer
> 0 votes
You need to render your form in the template. Simply calling drupal\_get\_form won't suffice. To render the form use following:

drupal\_render(drupal\_get\_form('form\_nam'))

You also need to ensure the following:

* In your custom form #theme parameter is set to appropriate theme function.
    + Further the hook\_theme implementation is correct.

Refer this link for a working example

---
Tags: 7, theming, forms
---


# Question
Title: How to load an include file from Drupal's include folder?
I am experiencing a problem with the GlobalRedirect module in that it seems like it is not loading the locale.inc which it relies upon. I tried using the module\_load\_include function but did not work as locale.inc isn't apart of a module.

I know I can use:

```
include(DRUPAL_ROOT."/includes/locale.inc");

```

Is there a Drupal specific function call to load include files for Drupal? I am curious if there is.

Thanks

# Answer
> 3 votes
With the help of module\_load\_include() method you can include the core files from the include directory the only thing is you need to pass "content" in the second parameter (i.e: module name).

Working Example on including a file from drupal core includes directory,

```
module_load_include('inc', 'content', 'includes/actions');

```

# Answer
> 8 votes
```
require_once DRUPAL_ROOT . '/includes/actions.inc';

```

is the correct way.

Using 'content' just worked, because there is no module named content and just did work due to a side-effect. It also caused silent performance problems on Drupal versions \< 7.50.

There is no Drupal specific function to load a core include file, and this is how it is done in includes/common.inc line 5242.

* Fabianx, Drupal 7 core branch maintainer and core committer

---
Tags: 7
---


# Question
Title: How to add a Rules Condition to only allow voting for users with at least 30 user points?
I want to put condition when userpoints\>=30, then user is able to vote.

For this, I did following steps-

* ON event- "User votes on a node" the condition selected is "Compare current Userpoints" and in the condition part put "\>=30".

I am using following modules: Rules, User Points and Vote Up/Down.

# Answer
> 2 votes
You should try to implement the hook form alter Drupal API: hook\_form\_alter

Within the hook\_form\_alter you can validate, if the current user has more then 30 Points and disable the voting widget if the value is below 30.

# Answer
> 0 votes
There seems to be a contradiction in what you are asking for:

* '***... ON event- "User votes on a node" ...***': if that (Rules) Event has been triggered, then the vote has already been completed.
* '***If ... then user is able to vote ...***': if the condition is NOT satisfied, the user should NOT be able to vote.

To resolve that contradiction, IMO you should only **allow** voting for users which have at least 30 user points. Here is a technique to get that to work:

* Grant some permission when a user's amount of user points reaches 30, and take that permission away again if it gets reduced to some amount below that. The obvious permission to be used for this is by using the role which allows voting.
* Monitor changes in user points for a user, by using the Rules module like so:

+ Use the Rules Event that captures user points being rewarded (whereas such points can be negative also ...).
    + Use the Rules Event (or Rules Action!) as described in How to access current amount of earned userpoints in a Rules Condition? (be aware that there is no out-of-the-box Rules Condition like "does this user have at least 30 user points"?).
    + Perform a Rules Action to grant access to the role that allows voting, when the user's amount of user points is at least 30 (and revoke that access if it is below 30). If you'd also use the Conditional Rules module, you can perform both types of Rules Actions (grant and revoke) in a single rule.

---
Tags: users, rules, userpoints, rating
---


# Question
Title: Edit old revision without changing the current revision
I'm using revisions to keep a public archive of changes in my nodes. Is it possible for me to edit an old revision of a node (both the message and the fields) directly, and not change the current revision? Basically, what I'm trying to do is what the User Revision Edit module does, but for nodes.

So far, in my custom module, I have something like this (notice that I'm also using the Revisioning module):

```
/**
 * Implements hook_menu().
 */
function node_revision_edit_menu() {
  $items['node/%node/revisions/%vid/modify'] = array(
    'title' => 'Modify this revision',
    'load arguments' => array(3),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('node_revision_edit_form', 1, 3),
    'access callback' => '_node_revision_edit_link_access',
    'access arguments' => array('modify revisions'),
    'file' => 'node_revision_edit.admin.inc',
  );
  return $items;
}

```

and the essence of the logic that I'm trying to apply:

```
function node_revision_edit_form($form, &$form_state, $node, $vid) {

  // Prepare loading the node edit form
  form_load_include($form_state, 'inc', 'node', 'node.pages');

  // Populate the form state.
  $form_state += form_state_defaults();

  // Save the form id for the current content type.
  $nfid = $node->type . '_node_form';

  // Rebuild the entire user edit form for our needs
  $form = drupal_retrieve_form($nfid, $form_state);
  drupal_prepare_form($nfid, $form, $form_state);

  // Setup the already existing log in the field
  $form['revision_information']['log']['#default_value'] = node_revision_list($node)[$vid]->log;

  // Set the "Modify current revision, no moderation" as the default revision operation
  $form['revision_information']['revision_operation']['#default_value'] = 0;

  // Unset the options that we do not need
  // unset($form['options']);

  // Create a new submit button since we do not want to invoke the standard callback functions
  unset($form['#submit']);
  $form['#submit'] = array('node_revision_edit_form_submit');

```

My problem is that I have no idea as to where to go from here. I obviously can't use node\_save since it automatically handles revisions. Any ideas on what my next step should be? Is there a function that I'm missing and could be useful for my problem? Or will I have to go for direct database edits?

Any feedback is greatly appreciated.

# Answer
After spending some time browsing through the code of node\_save() to figure out exactly how it works and testing various methods, I managed to solve my problem by performing the following steps:

1. Load the node's revision that the user selected to edit
2. Set the node's properties from the values retrieved from the $form\_state
3. Call node\_save for the specific $node object
4. Since the newer revisions' state changes to "pending approval", I also have to save the latest revision of the node with node\_save so that it becomes current again

My submit callback function looks like this:

```
/**
 * Submit callback for edit revision form.
 */
function node_revision_edit_form_submit($form, &$form_state) {

  // Store the values that we will be needing
  $nid = $form['nid']['#value'];
  $vid = $form['vid']['#value'];

  // STEP 1
  $node = node_load($nid, $vid, FALSE);
  $latestvidobj = array_shift(node_revision_list($node));
  $latestvid = $latestvidobj->vid;

  // STEP 2
  $node->title = $form_state['values']['title'];
  $node->log = $form_state['values']['log'];
  $node->field_tags = $form_state['values']['field_tags'];
  $node->field_law_article_body = $form_state['values']['field_law_article_body'];

  // These are entity reference fields that accept unlimited values
  // I had to unset an 'add_more' variable that is left over in the $form_state
  unset($form_state['values']['field_article_modifies'][LANGUAGE_NONE]['add_more']);
  unset($form_state['values']['field_article_is_modified'][LANGUAGE_NONE]['add_more']);

  // And then remove an empty array left in there
  $tempfam = array_pop($form_state['values']['field_article_modifies'][LANGUAGE_NONE]);
  $tempfaim = array_pop($form_state['values']['field_article_is_modified'][LANGUAGE_NONE]);
  // Then set the $node's properties
  $node->field_article_modifies = $form_state['values']['field_article_modifies'];
  $node->field_article_is_modified = $form_state['values']['field_article_is_modified'];

  $node->field_law_free_tags = $form_state['values']['field_law_free_tags'];
  $node->field_law_article_extra_notes = $form_state['values']['field_law_article_extra_notes'];

  // STEP 3
  node_save($node);
  // STEP 4
  $latestnode = node_load($nid, $latestvid, FALSE);
  node_save($latestnode);

  // Log the revision save
  watchdog('node', "Modified node id: {$nid} and revision id: {$vid}.");

  // Notify the user that the revision was edited succesfully
  drupal_set_message(t('Updated revision %vid of node %nid.', array('%vid' => $vid, '%nid' => $nid,)), 'status');

  drupal_goto('node/' . $nid . '/revisions/' . $vid . '/list');
}

```

I don't like this code, since it's case-specific and I would like to find a more abstract way of passing the $form\_state\['values'\] to the $node object. Since I have some other requirements from my editors (like the option to rearrange the revisions), I will try to find a cleaner way to do it and post it here (I may package it as a separate module and post it in drupal.org once the project is done).
> 0 votes

# Answer
I'm afraid that not even `_node_save_revision` allows that. Revisions were designed to keep old stuff archived and unchanged. Of course sometimes we need to violate that principle for the sake of moderation.

You will have to smartly adapt piece from above function:

```
$node->uid = $uid; // Make sure revision's author stays unchanged
drupal_write_record('node_revision', $node, $update);

```

I don't have time to experiment with it, but I'm sure you will find out pretty easily.

Carefully consider if you want to also call

```
module_invoke_all('node_presave', $node);
module_invoke_all('entity_presave', $node, 'node');

```

before save, and

```
module_invoke_all('node_' . $op, $node);
module_invoke_all('entity_' . $op, $node, 'node');

```

after save. Probably **you don't**, but it depends - some modules may use revision data for search or other purposes.

Last but not least: I must admit I have no idea how `field_attach_update` handles field revisions.
> 2 votes

# Answer
Both node\_save and field\_attach\_update can be used to update old revisions. The issue is that they also update the current revision. Other revisions are left unchanged. Node\_save updates the last edited time/date, which is undesirable when updating an old revision, so field\_attach\_update could be a better option.

```
<?php

$nid = 1; //node id
$vid = 5; //revision no

$loaded_node = node_load($nid, $vid);
$original_node = node_load($nid);

//make changes to old node version here
$loaded_node->field_tags[LANGUAGE_NONE][0]['tid'] = '1';

//save the old node revision. unfortunately this updates the current node too.

field_attach_update('node', $loaded_node);
//    node_save($loaded_node); //this is possible here too

//replace the current node with its original content
field_attach_update('node', $original_node);
//    node_save($original_node); // this works but changes the last modified time etc of the current node

?>

```

You would normally then flush the cache for the given node after performing field\_attach\_update, however this might not be necessary as wouldn't imagine old revisions are cached and the current node is unchanged.

drupal\_write\_record would also work to make a modification at the database level, but means you are working with the database rather than a node object.
> 1 votes

---
Tags: 7, nodes
---


# Question
Title: Cannot add 'Page Title' and 'Main Content' blocks to panel
Configuration:

* Drupal 8.1.5
* Panels 8.x-3.0-beta4
* Page Manager 8.x-1.0-alpha23
* Layout plugin 8.x-1.0-alpha22
* Panelizer 8.x-3.0-alpha2

When I create a Panel variant for `/node/{node}` with Page Manager, I can add field blocks, like

* `entity_field:node:title`
* `entity_field:node:body`

These get rendered.

However, if I add blocks

* CORE / Page Title (`page_title_block`)
* SYSTEM / Main page content (`system_main_block`)

these render to nothing. Can someone explain why?

# Answer
Answering my own question after I found some more info.

This is indeed a bug, hopefully to be fixed soon: https://www.drupal.org/node/2626090
> 0 votes

---
Tags: 8, panels
---


# Question
Title: How set a time type field programmatically?
I create a custom content entity type.

I want one field for the event time.

Since there is no time field, but a dataTime\_type, I create a plugin for a custom field :

> FieldType : TimeItem.php

```
/**
 * Plugin implementation of the 'time' field type.
 *
 * @FieldType(
 *   id = "time",
 *   label = @Translation("Time Field"),
 *   description = @Translation("Permet la creation d'un champ de type time"),
 *   default_widget = "time_widget",
 *   default_formatter = "time_formatter"
 * )
 */

  /**
   * {@inheritdoc}
   */
  public static function schema(FieldStorageDefinitionInterface $field_definition) {
    return array(
        'columns' => array(
            'value' => array(
                'description' => 'The time value.',
                'type' => 'int',
                'length' => 6,
            ),
        ),

    );
  }

```

I try to change type to time (for mysql) but mysql error return me a null for the type. So I use int for store time in seconde.

> FieldWidget : TimeWIdget.php

```
/**
* {@inheritdoc}
*/
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$value = isset($items[$delta]->value) ? $items[$delta]->value : '';
$element += array(
'#type' => 'time', //HTML5 input
'#default_value' => $value,
'#size' => 4,
'#element_validate' => array(
array($this, 'validate'),
),
);

return $element;
}

```

My entity :

```
 $fields['heure_evenement'] = BaseFieldDefinition::create('time')
        ->setLabel(t('test'))
        ->setDescription(t('test'))
        ->setRequired(TRUE)
        ->setDefaultValue('')
        ->setDisplayOptions('view', array(
            'label' => 'above',
            'type' => 'string',
            'weight' => 3,
        ))
        ->setDisplayOptions('form', array(
            'weight' => 3,
        ))
        ->setDisplayConfigurable('form', TRUE)
        ->setDisplayConfigurable('view', TRUE);

```

All is working except one thing, the HTML5 input type **time**

Drupal know some input in html5 but not all... type tel, email, number, range, color, date, datetime is ok but not the type time alone.

So I was hoping get it with a custom plugin, but no...

**Edit 1**

The only way I have found is to create 2 select for this type :

```
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$value = isset($items[$delta]->value) ? $items[$delta]->value : '';

    //heure
    for($i=0;$i<=24;$i++){
        $hour[]=$i;
    }

    //minutes
    for($i=0;$i<=59;$i++){
        $minutes[]=$i;
    }

$element += array('hour'=>array(
    '#title'=>t('Hour'),
    '#type' => 'select',
    '#options'=>$hour,
    '#default_value' => $value,
    '#element_validate' => array(
    array($this, 'validate'),
    ),
)
);

    $element += array('minutes'=>array(
        '#title'=>t('Minutes'),
        '#type' => 'select',
        '#options'=>$minutes,
        '#default_value' => $value,
        '#element_validate' => array(
            array($this, 'validate'),
        ),
    )
    );

return $element;
}

```

Any idea about this?

# Answer
> 12 votes
The form element property `#type` refers to an element type, not a HTML element. It is okay to define your own element types (or theme types), and you can provide your own markup for it. This can be done by implementing a RenderElement plugin.

Update:

You can also use the `datetime` render element and disable the date portion.

`$element['#date_date_element'] = 'none';`

Update 2:

The comment form has an example of a render array that uses the `datetime` type. So given that as a guideline,

```
  $form['time_without_date'] = array(
    '#type' => 'datetime',
    '#title' => $this->t('Time without date'),
    // HTML 5 time element format can be H:i
    '#default_value' => DrupalDateTime::createFromFormat('Y-m-d H:i:s', '1970-01-01 20:00', 'UTC'),
    '#size' => 20,
    '#date_date_element' => 'none',
    // This sets html 5 time element use explicitly, probably not necessary.
    '#date_time_element' => 'time',
  );

```

---
Tags: entities, 8, database, plugins
---


# Question
Title: How do I prevent accessing a page with /node/37 directly when an alias has been set?
I work with Drupal 8.

I've set an `url alias` for my page to `/nice-url`. When I acces it via `http://mypage.com/nice-url` everything works fine.

The problem is, this page is still accessable via `http://mypage.com/node/37` \- it's bad for SEO and it produces some mess.

Is it possible to remove that `http://mypage.com/node/37` page? I mean I want the content of that page to accessable **only** via `http://mypage.com/nice-url`.

# Answer
You don't want to deny access to it but simply redirect to the aliased URL.

That feature is provided by the Redirect module and there's also a core issue to make core do that automatically.
> 3 votes

# Answer
You could check the URI:

```
$uri = RequestStack $requestStack->getCurrentRequest()->getRequestUri();

```

If the URI is 'node/37' you can `throw new AccessDeniedHttpException();`

But I don't think that this will improve your SEO.
> 0 votes

---
Tags: 8, uri
---


# Question
Title: How to change the look of second article at front page
I generate articles with the help of VIEWS at front-page. But I want that the second article has a different look. So I want to add div-Tags and additional css-classes to that second article. I have tried to do this with a boolean field but the teaser does not have the possibility to check whether boolean field is true or false. Any idea how I can realize it??

# Answer
> 2 votes
One approach to do this is to use multiple views. One that displays only one node and a second one that displays the others, with an offset of one. Then it's easy to configure those views to use different view modes then. You can do that using Page Manager/Panels, Views attachments or possibly also core blocks.

One thing that can be a challenge to figure out is paging, depends on what you expect to see on the second page exactly. If you have paging, then a different approach might be necessary, for example by changing the view mode of the first view through code, through a preprocess hook or so.

---
Tags: views, theming, 8
---


# Question
Title: How to build a url to an (AJAX driven) exposed filter?
There are quite some threads about it, but none seems to do the job for me.

I'm using a *better exposed filter* on a view, and I'm trying to build a link that would expose the results by a query in the url.

Eg: *domain.com/myview?filter=term-id*

Why am I looking for this? When I use the regular approach (using Taxonomy display) it would use an url like this *domain.com/myview?filter=some-stuff*, and the exposed filter wouldn't work anymore but for the terms specified in the url. All the possible results are limited to what's in the url, while it should be able to filter on *all* the results, regardless of what's in the url.

In my console I found something like this when I'm using the exposed filters: *domain.com/en/views/ajax`?field_sector_tid=6`*

I wish I could translate that behaviour to an url. Anyone ha an idea how I can achieve this please?

# Answer
> 2 votes
If I understood well, once I face the same situation than you, the module Views Filter Harmonizer help me to solve my issue.

From the module's page:

> Views Filter Harmonizer solves an operational foible with the Views module regarding filtering.
>
> Normally, when a Views field has been assigned both an exposed filter and a contextual filter, then both filters get applied to the View's results set -- always. This is not configurable behaviour. It's hard-coded.

# Answer
> 0 votes
It looks like you can combine exposed and contextual filters using this module: https://www.drupal.org/project/filter\_harmonizer

---
Tags: 7, uri, views
---


title: Which version should I install?

text:
# Question
Title: Which version should I install?
Should I install Drush 8 or Drush 9 for Drupal 8?

What does the code status failing mean? Is Drush 8 not compatible with Drupal 8?

# Answer
> 4 votes
At the moment, the Drush unit tests have some intermittent failures. I wouldn't worry too much about the failure. I'd recommend Drush 8 for Drupal 8 use.

**UPDATE:** I looked into the test failures, and it looks like they are related to fact that Drupal 8.1.x is now the recommended version of Drupal, whereas the Drush 8 tests are still assuming 8.0.x. These test failures have been fixed in the master branch, but not back-ported to the 8.x branch yet. The failures are caused by problems in the tests, not by problems in Drush; they should be fixed shortly, but will not cause you any problems in the meantime.

---
Tags: drush
---


# Question
Title: How to use hook_views_query_alter to catch last DELTA of a multivalue date field?
I need a View that should list only past events.

Events have multivalue date fields, so an event can have multiple "start" and "end" dates.

Date's API assign a DELTA value to every group of "start" and "end" dates.

In my configuration, an event is consideret "past" if its very last (= last delta) end date is \< of "now" (= today)

With default Views UI it seems impossible to catch LAST delta of group of dates for a record.

(see some answers by Merlinofchaos here: https://www.drupal.org/user/26979)

My UI views provides the following query:

`SELECT field_data_field_period.delta AS field_data_field_period_delta, field_data_field_period.entity_id AS date_id_field_period2, field_data_field_period.delta AS date_delta_field_period2, node.created AS node_created, node.nid AS nid
FROM
{node} node
LEFT JOIN {field_data_field_period} field_data_field_period ON node.nid = field_data_field_period.entity_id AND (field_data_field_period.entity_type = 'node' AND field_data_field_period.deleted = '0')
WHERE (( (node.status = '1') AND (node.type IN ('exhibition')) AND (DATE_FORMAT(ADDTIME(field_data_field_period.field_period_value2, SEC_TO_TIME(7200)), '%Y-%m-%d') < '2014-07-16') ))
ORDER BY node_created DESC
LIMIT 10 OFFSET 0`

With some tests with pure SQL directly on DB, I noticed that I can obtain the results I want with the following changes to the query:

`SELECT MAX(field_data_field_period.delta) AS field_data_field_period_delta, field_data_field_period.entity_id AS date_id_field_period2, field_data_field_period.delta AS date_delta_field_period2, field_data_field_period.field_period_value2 AS field_data_field_period_field_period_value2, node.created AS node_created, node.nid AS nid
FROM node
LEFT JOIN field_data_field_period ON node.nid = field_data_field_period.entity_id AND (field_data_field_period.entity_type = 'node' AND field_data_field_period.deleted = '0')
WHERE (( (node.status = '1') AND (node.type IN ('exhibition')) ))
GROUP BY nid
HAVING MAX(DATE_FORMAT(ADDTIME(field_data_field_period.field_period_value2, SEC_TO_TIME(7200)), '%Y-%m-%d')) < '2014-07-15'`

In the above please notice:

1. field\_data\_field\_period.delta becomes MAX(field\_data\_field\_period.delta)
2. Added clause "GROUP BY nid" and "HAVING MAX(DATE\_FORMAT(ADDTIME(field\_data\_field\_period.field\_period\_value2, SEC\_TO\_TIME(7200)), '%Y-%m-%d')) \< '2014-07-15' "

After hours of research I understood I have to use hook\_views\_query\_alter to alter my views query, but the modification I need are very complex and I don't know where to start...

Please help me.

# Answer
This can be done with HOOK\_views\_query\_alter(). Add all the fields as normal within the views UI, including filtering on the date field value. Make sure the entity ID is in there (in your case, nid is in the query) and the date's delta field.

Next, add a WHERE clause on the delta in hook\_views\_query\_alter() using add\_where\_expression():

```
function MODULE_views_query_alter(&$view, &$query) {
  // Check for correct view
  if ($view->name == 'view_name' && $view->current_display == 'display_name') {
    $query->add_where_expression(0, 'field_data_field_period.delta = (SELECT MAX(field_data_field_period.delta) from field_data_field_period WHERE entity_id = nid)');
  }
}

```

This assumes the filter should be in the first filter group (0).

References:

https://api.drupal.org/api/views/views.api.php/function/hook\_views\_query\_alter/7.x-3.x

https://api.drupal.org/api/views/plugins!views\_plugin\_query\_default.inc/function/views\_plugin\_query\_default%3A%3Aadd\_where\_expression/7.x-3.x
> 1 votes

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


# Question
Title: How to theme the table view mode which is showing entities in inline entity form
I am looking for a D8 solution to theme the table view mode. To start, I would like to remove the main title (the "Legend" tag of the html fieldset).

Note: I know how to use hook\_inline\_entity\_form\_table\_fields\_alter to add/remove columns, I would like to theme what is **outside** the table.

After the remove of the title, I would like to remove the headers of the table ("Title", "Status", "Operations"...)

In fact, if someone have a solution, I would like to get rid of this table view mode.. My final goal is to have a very simple view mode showing only one field and the 2 action button..

Here is the solution I found to remove the header and the title: this is to preprocess fieldset and table hooks

```
/**
 * Implements hook_preprocess_fieldset().
 */
function my_module_preprocess_fieldset(&$vars) {
  //Remove the fieldset title/legend for field_myfield
  //as it is a multiple value field, I check only the
  //first part of the id to target field_myfield
  if (strpos($vars['attributes']['id'],'dit-field-myfield')>0){
    unset($vars['legend']);
    unset($vars['legend_span']);
    $vars['attributes']['style'][]='padding:0';
  }
}

/**
 * Implements hook_preprocess_table().
 */
function my_module_preprocess_table(&$vars) {
  //In my use case, I need to target only table that are
  //generated by ief module. I use the first part of the
  //id to target it
  if (strpos($vars['attributes']['id'], 'ef-entity-table')>0 ) {
    //remove column headers
    unset($vars['header']);
    //adpat layout;
    $vars['attributes']['style'][]='margin:0;border-collapse:separate';
  }
}

```

# Answer
> 0 votes
Most simple solution should be to override the table.html.twig template. You can simplify it to your needs in your theme's template directory. Use the core/themes/classy/templates/dataset/table.html.twig file as source to start your theming.

If you don't want to "re-theme" all tables, add "suggestions" for other templates to your tables and create template files accordingly.

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


title: Ajaxly login/signup in bootstrap modal

text:
# Question
Title: Ajaxly login/signup in bootstrap modal
This is sample modal sample of boostrap modal

```
<div id="signin" class="modal fade" role="dialog">
    <div class="modal-dialog">

        <!-- Modal content-->
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">×</button>
                <h4 class="modal-title">Modal Header</h4>
            </div>
            <div class="modal-body">
                <p>Some text in the modal.</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>
        </div>

    </div>
</div>

```

and this is a line trigger modal in `header.html.twig`,

```
 <li><a type="button" class="btn btn-lg navbar-btn" data-toggle="modal" data-target="#signup"> {{ 'SIGNUP'|t }}</a></li>

```

**goal:** open login form in bootsrap modal.

I find the name of file I can customize user-login block , it's `block--userlogin.html.twig` then my markup

```
<!-- Modal -->
<div id="signin" class="modal fade" role="dialog">
    <div class="modal-dialog">
        <!-- Modal content-->
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">×</button>
                <h4 class="modal-title">Login</h4>
            </div>
            <div class="modal-body">
                <form method="post" action="{{ path( "user.login" ) }}"   role="form" name="loginform">
                    {% if error %}
                        <div class="warning">
                            <h3>{{ "Could not login" }}</h3>
                            <ul>
                                <li>{{ "A valid username and password is required to login." }}</li>
                            </ul>
                        </div>
                    {% endif %}
                    <div class="form-group">
                        <input type="email" value="{{username }}"   name="_username" tabindex="1" class="form-control" id="email" placeholder="{{ "username or email :"|t}}">
                    </div>
                    <div class="form-group">
                        <input type="password" class="form-control" id="pwd" ame="_password" placeholder="{{ "Password"|t }}">
                    </div>
                    <div class="checkbox">
                        <label><input type="checkbox"> Remember me</label>
                    </div>
                    <button type="submit" class="btn btn-default">{{ "Sign In"|t }}</button>
                    <input type="hidden" name="_csrf_token" value="{{ csrf_token }}" />
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>
        </div>

    </div>
</div>

```

**but** with this action `action="{{ path( "user.login" ) }}"` it redirect me to `user/login` page. **I want to know how can I login/signup usuer ajaxly in modal without redirect to user/login page?**

# Answer
There are two questions:

**1.) goal: open login form in bootsrap modal.**

In your code by redirecting to a new path the page will reload, and not display a modal login.

But you don't need a new path, your form is already there. It is in the block content and you should be able to place `{{ content }}` in the bootstrap modal dialog like this.

**block--userlogin.html.twig:**

```
<div id="signin" class="modal fade" role="dialog">
    <div class="modal-dialog">

        <!-- Modal content-->
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">×</button>
                <h4 class="modal-title">Modal Header</h4>
            </div>
            <div class="modal-body">
                {{ content }}
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>
        </div>

    </div>
</div>

```

**2.) ajaxifing the login (not reloading *after* submit)**

For this there is some work to do, you can see this in the D7 module:

https://www.drupal.org/project/ajax\_register

For D8 you need to code something similar.
> 3 votes

# Answer
```
function YOUR_THEME_preprocess_page(&$variables) {
  // You will most likely want to show and render the form for anonymous users.
  $variables['login_form'] = FALSE;
  if (!\Drupal::currentUser()->id()) {
    $form = Drupal::formBuilder()->getForm(Drupal\user\Form\UserLoginForm::class) ;
    $render = Drupal::service('renderer');
    $variables['login_form'] = $render->renderPlain($form);
  }
}

```

Put `{{ login_form }}` in your twig file
> 0 votes

---
Tags: theming, forms, users, 8, ajax
---


# Question
Title: Search API / Facets: How can I define a range / manipulate the search query in D8?
I've defined a facet for the field "Authored on". I'd like to create display filters like "current week", "current month", etc. on my website.

The creation of the links was no problem. I have facet links like this:

```
<a href="/news?period=current_week">Current week</a>

```

How can I manipulate the search query if a period has been selected? I need something like "get all search results, which are younger than tstamp of monday this week" or "get all search results between date X and date Y".

# Answer
Afterwards here my solution: I've solved it with condition groups in the hook\_search\_api\_query\_alter() function:

```
function MYMODULE_search_api_query_alter($query) {
    //...

    $conditionGroup = $query->createConditionGroup('AND');
    $conditionGroup->addCondition('created', $firstDayOfYear, '>=');
    $conditionGroup->addCondition('created', $lastDayOfYear, '<=');
    $query->addConditionGroup($conditionGroup);

    //...
}

```
> 3 votes

# Answer
You cannot do this easily to my knowledge.

I recently looked at the Search API (7x) module for similar functionality and basically you can do preconfigured Ranges using these modules:

(7x) https://www.drupal.org/project/search\_api\_ranges this modules treats a range value as a numeric values, which dates are essentially not. Converting to timestamps is a pita.

(7x) the Search API does not support the `BETWEEN` operator of Solr yet directly for Views integration. See https://www.drupal.org/node/1783746

The only alternative I've found for date searching with Solr (using Search API) is basically 2 exposed filters in Views going off of an Indexed date field in Solr. And then configuring the filter to use the date\_popup widget for a nice calendar with day, month and year selection options -- but it's not a simple range or slider widget.

You may get better mileage from the Apache Solr module instead of Search API but I use the Search API module because I can see with little effort it supports Solr 5.x in the module include files.
> 0 votes

---
Tags: 8, search
---


# Question
Title: How to unpublish a node with vocabulary term X after Y hours?
How could I automatically unpublish a node after Y hours (e.g. after 24h after it appears on-line) but only when it has a specific category - category is based of course on taxonomy's vocabulary.

Important is that an editor has no influence on number of hours after which the node is unpublished - so it must be predefined by the admin.

# Answer
> 3 votes
Use the Rules module for this, by performing these steps:

* Create a Rules Component to unpublish a node, which is like a getting started with Rules Components.
* Create a Rule like so:

+ Rules Event: After saving a new node.
    + Rules Conditions: check if "*it has a specific category - category is based of course on taxonomy's vocabulary*" (as in your question).
    + Rules Action: schedule the execution of the Rules Component, to be executed after 24 hours. You'll have such Rules Action available if you enabled the `rules scheduler` (sub-module of Rules). This will actually execute the Rules Component "next time cron runs". So make sure to take that into account also to set the frequency of your cron jobs, and/or schedule the Rules Component a bit before the 24 hours have passed (whatever fits for your case). Note that the one who can edit the rule will be able to "predefine" when the Rules Component will be executed.

# Answer
> 2 votes
One of the option is, use the Scheduler module.

> Scheduler gives content editors the ability to schedule nodes to be published and unpublished at specified dates and times in the future.
>
> Dates can be entered either as plain text or with calendar popups. To use calendar popups in Drupal 7 you need to install the Date Popup module, which is part of the Date module. In Drupal 8 this is built into Core.

---
Tags: 7, nodes, taxonomy-terms
---


# Question
Title: Where does the theme name get stored in database?
In which table does Drupal 8 store the theme name?

I'm trying to programmatically install an uninstalled theme. Obviously, there's some written logic behind the *Install and set as default* button. What exactly does that button do?

# Answer
> 0 votes
The theme names are not stored in the db; other wise, we would have to uninstall the uninstalled themes... How would Drupal know the name of an uninstalled theme? It reads the names from the **themename.info.yml** file.

If you think about it, its just like uninstalled module names, the module name is not stored in the db, Drupal reads/gets the name from the module.info.yml file.

---
Tags: theming, 8
---


# Question
Title: Links don't work on the production server after moving from the development server
I have moved my Drupal site from localhost to live server but all links and contents are not access able and it gives:

> 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.

I have tried:

* clearing all caches, session and watchdog tables
* replacing all localhost links on the exported sql file with live site name
* changing database connection info on setting.php file

Still I have no luck.

# Answer
This sounds like missing .htaccess file. Check if this file exists or not. If not, upload a standard drupal htaccess file.

You can use this one maybe. https://github.com/drupal/drupal/blob/7.x/.htaccess
> 1 votes

---
Tags: caching, .htaccess
---


# Question
Title: How to make Drupal 8 use only relative URLs?
I'm trying to get my site to use only relative URLs, like in the question drupal.stackexchange.com/questions/105932

**EDIT 3:** It seems like Drupal 8.0.3 and beyond will do this by default:

https://www.drupal.org/node/2650374

But I've changed the code for Drupal 8 to this by getting rid of the deprecated function:

```
function custom_file_url_alter(&$uri) {
  global $base_path;

  $scheme = file_uri_scheme($uri);

  if (!$scheme || $scheme == 'public') {
    if (!$scheme) {
      $path = $uri;
    }
    else {
      ////$wrapper = file_stream_wrapper_get_instance_by_scheme($scheme);
      $wrapper = \Drupal::service('stream_wrapper_manager')->getViaScheme($scheme);
      $path = $wrapper->getDirectoryPath() . '/' . file_uri_target($uri);
    }

    // Clean up Windows paths.
    $path = str_replace('\\', '/', $path);

    $uri = $base_path . ltrim($path, '/');
  }
}

```

The problem is, whenever I add even just an article with an image (or any content type with a file in it) I get an error like this: `'Uncaught PHP Exception InvalidArgumentException: "The URI '/sites/default/files/field/image/h.jpg' is invalid. You must use a valid URI scheme." at /srv/www/example/core/lib/Drupal/Core/Url.php line 301, referer: http://example.com/node/add/article`. I'm also getting this error when visiting a page that links to certain uploaded files.

The documentation says that this hook is called whenever the file\_create\_url method is called, but I don't know enough about Drupal to understand what scenario this method is being called which is causing Url.php to get mad at me. For what reasons does Drupal call file\_create\_url, and why are almost all scenarios working for me while some are freaking out about no scheme being used?

Any extra information or guidance about this will be appreciated.

**EDIT:**

Here are some examples of $uri as it comes into the function (1) and as it leaves (2) .

`1: 'core/themes/stable/images/core/icons/5181c6/pencil.svg'
 2: '/core/themes/stable/images/core/icons/5181c6/pencil.svg'
 1: 'public://css/css_Ys2L0rGQLjkWZQC7f9g5LiLUni8xUQvB1HqJHn3TKK4.css'
 2: '/sites/default/files/css/css_Ys2L0rGQLjkWZQC7f9g5LiLUni8xUQvB1HqJHn3TKK4.css'
 1: 'public://field/image/h_0.jpg'
 2: '/sites/default/files/field/image/h_0.jpg'`

The h\_0 example is one that happened after I created an article with the h.jpg image, which crashed and prevented creation of the article. I've noticed that when I upload the image using the form, the little ajax thing that happens and shows you the preview of the image doesn't work when I use this file\_url\_alter code. So, something is trying to call file\_create\_url when saving the image in the first place, and then, since the image is not properly saved, it can't be added as a field of the node.

Also, I've printed a backtrace, and it seems the crash happens after ThemeManager.php's render function calls template\_preprocess\_file\_link(), which, in file.module, tries to do this: `$variables['link'] = \Drupal::l($link_text, Url::fromUri($url, $options));`

...which caused the error I mentioned in the first place.

**EDIT 2:**

I've made this work by modifying one line of core. I changed the last line of template\_preprocess\_file\_link() in file.module from `$variables['link'] = \Drupal::l($link_text, Url::fromUri($url, $options));` to `$variables['link'] = $url;`. This makes all URLs relative without any noticeable issues. Does anyone know how to achieve this without hacking core? Or, does anyone know what negative effects doing this might cause?

# Answer
Maybe you can take a look at this function new to Drupal 8 :

file\_url\_transform\_relative()

Once you pass an `uri` through `file_create_url()` you get an absolute `url`. You can then pass it to `file_url_transform_relative()` and you'll get the relative path if indeed it's pointed to a local file.
> 2 votes

---
Tags: 8, uri
---


# Question
Title: How to prevent user point totals from going below a threshold for a given user?
I'd like to set an absolute floor for an individual user points (using the User Points module). Specifically, to make it impossible to have a total number of user points below 1.

In Drupal 6 there was the `userpoints_no_negative` module in Userpoints\_contrib, but this was removed in favour of Rules integration for 7.x (https://drupal.org/project/userpoints\_contrib).

The documentation provides an example using rules to evaluate point totals with a condition of "Userpoints - Compare current Userpoints" (https://drupal.org/node/874390), but **I am not finding this condition available**.

I'd accept any solution, be it using rules or a custom module.

---

EDIT 2/4/2014 9:17PM UTC - Example code based on ramesh babu's accepted answer:

```
/*
 * Implements hook_userpoints().
 * Checks if points at minimum threshold, corrects to 1 if pushed below limit.
 * Based on comments in Userpoints API documentation on D.O. a separate transaction
 * is made to correct for the threshold rather than modifying the points for
 * the existing transaction.  See https://drupal.org/node/206558
 */
function mymodule_userpoints($ops, $params) {
  if ($ops == 'points before' && !isset($params['threshold'])) {
    $future_total = userpoints_get_current_points($params['uid'], 'all') + $params['points'];
    if ($future_total < 1) {
      $params['description'] = 'Minimum point correction.';
      $params['points'] = abs($future_total) + 1;
      $params['threshold'] = true;
      userpoints_userpointsapi($params);
    }
  }
}

```

The documentation for the Userpoints API on drupal.org is also a helpful resource https://drupal.org/node/206558

# Answer
Here the solution with custom module implementation:

implement hook\_userpoints($op, $params) function in your custom module to check the user points in every transaction with two option called points before and points after.

For your thing check if the points are less than your threshold value, set your threshold value after the transaction.

for more referencehttp://api.worldempire.ch/api/userpoints/functions?page=1 check this.
> 3 votes

# Answer
I achieved this with the following rule:

```
{ "rules_prevent_negative_points" : {
    "LABEL" : "Prevent negative points",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "Points" ],
    "REQUIRES" : [ "php", "rules", "userpoints_rules" ],
    "ON" : { "userpoints_event_points_awarded_after" : [] },
    "IF" : [
      { "php_eval" : { "code" : "$num_pts = userpoints_get_current_points($userpoints_transaction->uid, \u0027all\u0027);\r\nif ($num_pts \u003C 0) {return TRUE;}" } }
    ],
    "DO" : [
      { "userpoints_rules_get_current_points" : {
          "USING" : { "user" : [ "userpoints-transaction:user" ], "tid" : "all" },
          "PROVIDE" : { "loaded_points" : { "negative_amount" : "Negative amount of points." } }
        }
      },
      { "data_calc" : {
          "USING" : { "input_1" : [ "negative-amount" ], "op" : "*", "input_2" : "-1" },
          "PROVIDE" : { "result" : { "pos_value" : "Positive value." } }
        }
      },
      { "data_calc" : {
          "USING" : { "input_1" : [ "pos-value" ], "op" : "+", "input_2" : "1" },
          "PROVIDE" : { "result" : { "result" : "result" } }
        }
      },
      { "data_convert" : {
          "USING" : {
            "type" : "integer",
            "value" : [ "result" ],
            "rounding_behavior" : "down"
          },
          "PROVIDE" : { "conversion_result" : { "points" : "Points needed to become 1" } }
        }
      },
      { "userpoints_action_grant_points" : {
          "user" : [ "userpoints-transaction:user" ],
          "points" : [ "points" ],
          "tid" : "0",
          "entity" : [ "" ],
          "description" : "Prevent negative amount of points.",
          "operation" : "Add",
          "display" : 0,
          "moderate" : "approved"
        }
      }
    ]
  }
}

```

Simply import it at `Configuration > Workflow > Rules`.
> 2 votes

# Answer
For Drupal 7, there is no Rules Condition related to the current total user points for a user. Except by using custom PHP code as in this example (which is similar to the Rules condition in Jeroen's answer, and which you could use in a Rules Condition *Execute custom PHP code*, e.g. to do some type of comparison):

```
global $user;
$current_points = userpoints_get_current_points($user->uid, 'all');
if ($current_points < 0) {return TRUE;}

```

However, there is a Rules Action "***Load user points of a user***", whereas you can ask for either a specific category, or for all categories together. This Rules Action provides a Rules variable (for which you can specify its name and description) which contains the amount of user points for the requested category. You can then use this variable in subsequent Rules Actions.

If you then want to use that variable within a Rules Condition, you have 2 ways of doing so:

* Include the condition in a Rules Component, whereas you trigger the execution of that Rules Component via a Rules Action following the "Load user points of a user" (and passing the variable containing the amount of user points as a variable for the Rules Component).
* Use the Conditional Rules module, so that you can specify Rules Conditions within Rules Actions.

Here is a basic example that displays a message about the current total user points for a user, after the user performed an update of some node (= the Rules Event, which you can change to any Rules Event that you want ... eg: replace it by "Drupal is initializing" to display the message on every path of your site):

```
{ "rules_display_userpoints_after_updating_content" : {
    "LABEL" : "Display userpoints after updating content",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "userpoints_rules", "rules" ],
    "ON" : { "node_update" : [] },
    "DO" : [
      { "userpoints_rules_get_current_points" : {
          "USING" : { "user" : [ "site:current-user" ], "tid" : "all" },
          "PROVIDE" : { "loaded_points" : { "total_points" : "Number of points in all categories together" } }
        }
      },
      { "drupal_message" : { "message" : "You now have [total-points:value] points" } }
    ]
  }
}

```

Use the Rules UI to import the above rule in your own site if you want.

To actually ensure the amount of user points is never below your threshold, perform Rules Actions similar to the Rules Actions shown in Jeroen's answer (using a Rules Component, or Conditional Rules, as explained above).

With that, you have another Rules based solution **which does not require custom PHP code** (in your Rules Condition).
> 1 votes

---
Tags: 7, userpoints
---


# Question
Title: Drupal 8 upload and embed a video to WYSIWYG
So what I am searching for is a module that gives us the exactly same functionality that we already have with the image tool in Drupal 8 in the WYSIWYG editor. And that should be working with just uploaded videos. I found that this module should be doing it for D7 - https://www.drupal.org/project/video

And also this module https://www.drupal.org/project/video\_embed\_field is doing it for D8, but only for videos from per say YouTube, Vimeo etc.

So please let me know if you found a way to add a similar to the image (see attached screenshot) but for video

Cheers and thanks in advance!

# Answer
> 1 votes
For simple solution Just get `video_embed_field` which includes module `Video Embed WYSIWYG` Enable both of them. You will get options to configure your WYSIWYG here `admin/config/content/formats/manage/full_html`. Just add the Video button in toolbar and checked the option `Video Embed WYSIWYG`. I hope you get what you want. Thanks

---
Tags: files
---