title: How to monitor comment / reviews?

text:
# Question
Title: How to monitor comment / reviews?
What is the best way to set up a page on which people could leave reviews, stories etc (I guess like on Yelp?). It would be a bonus if they could upload images, and or it used gravatars etc.

Additionally, we would need to monitor these posts, where the admin would be notified and then could approve them before they appear on the front end.

# Answer
> 2 votes
Drupal ships with that functionality you are describing out of the box, I mean the comments entity. Can be administered -approved, published, deleted etc- under `admin/content/comment` and are fieldable (`admin/structure/types/manage/%node-type/comment/fields`) and themable (`admin/structure/types/manage/%node-type/comment/display`).

Don't forget the comment's API

# Answer
> 1 votes
# Part 1 - Workflow

Just start with the typical content types (create your custom versions of it), and standard comments. Then add the modules mentioned below to get going.

### Workflow

Use the Workflow module to "*monitor posts*" (as in your question) before they actually get published. Here are some typical values you may want to use for the actual workflow management:

* Draft
* Needs review
* Needs work
* Published

### Rules

Use the Rules module to add all sorts of custom logic:

* based on something happening on the site (= Rules Event), eg: a comment is posted.
* perform all sorts of validations (= Rules Conditions), eg: check if the author of the post is also the author of the comment.
* automagically perform additional operations (= Rules Actions), eg: send an eMail notification to the author of a post.

# Part 2 - Monitoring

To actually monitor such post and notify an administrator, you could take advantage of the Menu Badges module: this module can be used, among other things, to create a custom view with a menu tab (say) "content to be reviewed" within `admin/content`. Similar to what is shown in the video Defining Menu Badges with Views in Drupal.

Refer to How to implement Administration UI notifications for new revisions? for more details about this interesting module.

# Answer
> 1 votes
I would recommend using https://www.drupal.org/project/reply (Reply module).

Reply is basically a fieldable entity so you can create a 'review', 'comment', 'forum post' or whatever you like by creating bundles and attaching fields to them. Such bundles can be attached to any fieldable entity by 'reply field'.

You can create as many fields as you would like. It also provides templates to override the behaviour. And most important without any customisations, you can have review individual page.

You can set access for reading and writing, position the form to the same page as entity or to a custom page, allow or deny replying to replies(= no hierarchy), choose threaded or flatted list. Such settings can be set for bundle, field, instance and entity with build-in inheritance which makes if a four level hierarchy settings system.

---
Tags: comments, rating
---


# Question
Title: How to bind to AJAX complete event in regard to styling the AJAX button submit throbber
With this I can bind to the AJAX button submit event:

`Drupal.ajax.prototype.beforeSend = function (xmlhttprequest, options) {
...
}`

My question, how to bind to the opposite (i.e. when AJAX button submit finishes)? Thanks.

# Answer
You can use `success` function. You can refer this for its usage.

```
/**
 * Handler for the form redirection completion.
 */
Drupal.ajax.prototype.success = function (response, status) {
  ...
}

```
> 1 votes

---
Tags: forms, ajax
---


title: Where do I store custom values/content?

text:
# Question
Title: Where do I store custom values/content?
I'm creating a page "from scratch", with routing, controller, etc. The content of my page is created by code, buy I want to add a editable component (the description of the page).

I don't want to use blocks, because I don't wanto to give too many permissions to editor role.

I could create a "custom content" content type to store content and then add node content from code.

Other ways? I was thinking to use configurations, but if I export all configurations with "drush cex", this config will be overridden after editing. A good way could, if it's possibile, to exclude this single component from export.

Other ideas?

# Answer
I am not sure about what is the question here. In general:

If you want to store content, create a ContentEntityType that extends ContentEntityBase. If you want to create a configuration, create a ConfigEntityType that extends ConfigEntityBase.

What you need sounds like a ContentType where you create your main content by code and have another Form to add/modify the content of a "page description" field in the ContentType. Maybe you can also use "Node" that could save a lot work.
> 2 votes

---
Tags: 8
---


# Question
Title: How to distinguish between custom modules and contrib modules?
We have taken a project where we have to upgrade a site from d6 to d7.

But their module structure is poor, and does not distinguish between custom and contrib modules. We also want to know what's upgradable, and what isn't?

This would be helpful for sending project estimation.

Is there a way to do this using drush perhaps?

# Answer
> 6 votes
If you want know which module has been upgraded or not and what things upgrade in module then you can use hacked module of drupal.

Go to hacked module configuration and click on "list project" Let it do the work.It will process the modules and will check for the changes.

Once it completes the process you will get a list of module along with the number of changes done in the modules.

Now open the directory sites/all/modules/ and check the modules which are displayed in the list you got after hacked process.The listed modules in the result are the contrib modules and rest of the modules should be custom.

# Answer
> 1 votes
Found a way to do the first part, and list all the custom modules.

Quite cool approach I felt -:

```
grep -rL --include "*.info" "datestamp" .

```

Pipe to wc -l to see the number of custom modules `grep -rL --include "*.info" "datestamp" . | wc -l`

# Answer
> 0 votes
You can list all contrib modules by running:

```
drush pm-updatestatus

```

all other which will say:

> No release history was found ...

they're most likely custom modules.

---

Another way is to list all the `project` values from `.info` file and check whether the project exists in Drupal.org, e.g. using callback to `https://updates.drupal.org/release-history/project_name/7.x`. See: How to download programmatically a module?. E.g.

> `find . -name "*.info" -exec sh -c 'eval $(grep "project\s\+=.\+" "{}" | tr -d " "); curl -s "https://updates.drupal.org/release-history/$project/7.x" | grep "project_status" && echo {} is contrib || echo {} is custom' ';'`

---
Tags: 7, drush
---


title: Get Path from node ID

text:
# Question
Title: Get Path from node ID
I'm using a twig template for a custom block that have images to link to specific nodes. I actually have the node IDs, however generating a relative link doesn't always work. Some pages are using aliases like so 127.0.0.1/web/products and some are using nodes like 127.0.0.1/web/node/19 so using the same relative link doesn't always work. Note that my drupal instance is within a /web/ folder and not at just 127.0.0.1

My twig template looks like this

```
<div class="row columns">
    {% for key, image in imageurl %}
    <div class="large-4 medium-3 column">
        <a href="./node/{{ nid[key] }}">
            <img src="../sites/default/files/{{ image }}"/>
        </a>
        <div>
            {{ block_title[key] }}
        </div>
    </div>
    {% endfor %}
</div>

```

When it appears on 127.0.0.1/web/products the link is

```
http://127.0.0.1/web/node/15

```

When it appears on 127.0.0.1/web/node/19 the link is

```
http://127.0.0.1/web/node/node/9

```

The image has the same issue, since 'image' only contains the filename. Is there a way I can automatically generate a link based on a node ID and a file that I know the path to, to account for URLs that may contain aliases?

# Answer
You should use Drupal 8 classes to generate the link. If you get the nid from an existing node object you can do the following in the .theme-file of your theme:

```
function yourtheme_preprocess_block(&$vars) {
  $node = Drupal::request()->attributes->get('node');
  $vars['link'] = $node->toUrl()->setAbsolute();
}

```

In twig you can output:

```
<div class="row columns">
    {% for key, image in imageurl %}
    <div class="large-4 medium-3 column">
        <a href="{{ link }}">
            <img src="../sites/default/files/{{ image }}"/>
        </a>
        <div>
            {{ block_title[key] }}
        </div>
    </div>
    {% endfor %}
</div>

```

To generate the URL of your node just knowing the nid (here in variable $nid) you can use the following in your .theme-file:

```
function yourtheme_preprocess_block(&$vars) {
  $options = array('absolute' => TRUE);
  $url = \Drupal\Core\Url::fromRoute('entity.node.canonical', ['node' => $nid], $options);
  $vars['link'] = $url->toString();
}

```

Again you can use {{ link }} to output the URL where ever you need in yout twig template.
> 3 votes

---
Tags: theming, 8
---


# Question
Title: How to implement challenges with prizes in a Drupal site?
I've been working on a Drupal Commerce site where you can buy goods with points. Users gain those points with a system I already implemented. Everything is fine, but now I have to implement challenges.

Basically, the users will need to "follow" the challenge, then every point they gain from that moment will fill their point meter of the challenge. Every user who reaches the point limit (specified when the challenge is created) will win a prize.

How can I do this? I was told that I could use the Flag module for the following part, but I'm really clueless.

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

# Configure the goals

Define some **goals**, with a description (say) like so:

* Challenge 1
* Challenge 2
* Challenge 3

For each goal you may optionally associated some image with it, which are typically used to visualize the goals completed by a user.

And after a goal is completed, you can (optionally) automatically grant a predefined amount of user points to the user who completed the goal.

# Configure the tasks

* To achieve *goal* "Challenge 1", define the **Task(s)** to be completed. E.g.:

+ Publish 1 (or some other amount of) articles.
    + Post 1 (or some other amount of) comments.
* To achieve *goal* "Challenge 2", define the **Task(s)** to be completed. E.g. publish 10 articles and post 20 comments.
* To achieve *goal* "Challenge 3", define the **Task(s)** to be completed. E.g. publish 25 articles and post 50 comments.

# Advanced task configuration

A more advanced way to use (configure) Goals, is to configure tasks like so:

* there could be multiple tasks to be completed for a single goal.
* some tasks might have to be repeated multiple times.
* some tasks might have to happen within a given timeframe.
* some tasks may require some amount of time to expire in between any 2 similar tasks.

# Track progress while performing tasks

To track the progress made by a single user to complete some task, you only have to write the appropriate rules, using the Rules module, to record relevant events happening in your site, which are related to the completion of the various tasks.

For the goals/tasks described above as an example, you'd only need 2 (extremely basic) rules, which would be triggered like so:

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

Note that these 2 rules can be re-used to measure progress on each of the 3 goals.

Moreover, the above challenges are pretty straight forward (basic) as examples of Challenges. But you can do this for virtually any entity for which you can think of a way to track them via the rules module.

# Process completed goals

After all tasks specific to a goal are completed by a user, the goal is automagically marked as completed. And the user points related to completing that goal will be rewarded.

If you want, you can also create additional rules that will be triggered (Rules Event) when a goal is completed by a user.

# More info

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

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

---
Tags: 7, commerce, flags
---


# Question
Title: How to write a Drush script to retrieve data?
I want to retrieve a field value by given nodes. Node has a field 'promo code'.

How can I retrieve `imageurl` value by giving 'promo code' field using a drush script?

What is the better way to do it?

I want to get data as a JSON or XML format for all the given nodes.

# Answer
You can start checking the code of the Drush Entity module.

> With drush entity you can query the entity system available for Drupal 8, 7 and (some of) 6.

And as Greg says you can use the Drushify module to start.

In this links you can find good references:
> 2 votes

---
Tags: drush
---


# Question
Title: How to change user badge when 'total User Points' increase?
I am building a community site, in Drupal 7, and using the User Points module and the User Badges module.

My goal is that every user will always have only one badge, that will be presented near the user's name, everywhere on the website.

These are my specifications for the badge to be selected according to the amount of User Points:

* 0-50 points = first badge
* 51-100 points = second badge
* 101-200 points = Third badge
* 201-300 points = Forth badge
* 301 points and more = Fifth badge

I tried to use User Points Contributed modules but unfortunately there is no Drupal 7 upgrade.

I tried using the Rules module, but didn't find a way to ***compare the current total amount of points of the user to my specifications***, (for Rules Event "*User was awarded points*"), so that based on the result of that comparison, the Rules Action would eventually change the badge assigned to the user.

Any suggestion to get this to work?

# Answer
The key part of your question seems to be this:

> I tried using the Rules module, but didn't find a way to ***compare the current total amount of points of the user to my specifications***, (for Rules Event "*User was awarded points*"), so that based on the result of that comparison, the Rules Action would eventually change the badge assigned to the user.

Indeed, for Drupal 7, there doesn't seem to be some Rules Condition related to the current total user points for a user. Except by using custom PHP code as in this example (which you could use in a Rules Conditionn *Execute custom PHP code* condition, 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, e.g. to "User was awarded points", as in your question):

```
{ "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.
> 2 votes

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


# Question
Title: Applying a patch that involve multiple modules
When I run apply patches to contributed modules, I download the patch, put it in the modules folder, and then execute `git apply patch patch_file_name` from that folder.

I never ran a patch for Drupal core, though, and I believe it's a bit different.

How can I apply a patch to Drupal core, which could involve multiple Drupal core modules?

# Answer
> 3 votes
Drush make is a method to maintain patched releases of contrib and core. It is the only organized, non-custom, method I know of for patch management. The makefile is self-documenting. By "self-documenting", I mean that the makefile contains a list of modules, their versions, and URLs of applied patches.

Create a makefile of an existing Drupal site with:

```
drush generate-makefile mysite.make

```

Note, as far as I know `drush generate-makefile` will not detect applied patches. The example makefile demonstrates how to reference patches in your makefile.

# Answer
> 1 votes
You can use `patch` command (read here for more). For eg. put the patch file in the folder where the file is stored for which the patch was written, then apply the patch.

```
patch < file.patch

```

**NOTE:** **for maintainability purposes, I follow these steps before and after the patch is successfully applied**.

* Make sure there is an issue in Drupal Core regarding the patch. If not then create one and upload the patch.
* Download the patch from the issue. If you use patch naming guidelines or Dreditor for patch name suggestion, then the patch will also have issue id. Also you can keep track of the issue to check if a better solution is available or the issue is closed(fixed).
* Make a folder in your Drupal installation inside **sites** folder or **root** folder and have a copy of the patch in there. This should be done so that if you update the Drupal Core, then your core changes will be removed and you can re-apply those patches using these copies.
* Delete the original patch from Drupal installation after the patch is used.

---
Tags: version-control
---


# Question
Title: Basic custom module installation error - "...Controller does not exist in ReflectionMethod"
I was following this tutorial to create an most simple custom module.

I have created files inside `/modules/elevator_search`:

And in the `/src/Controller` I've placed:

The `/modules/elevator_search/evelator_search.info.yml`:

```
name: Elevator Search
description: Moduł wyszukiwarki wind
package: Custom
type: module
version: 1.0
core: 8.x

```

The `/modules/elevator_search/evelator_search.module` is empty.

The `/modules/elevator_search/evelator_search.routing.yml`:

```
elevator_search.content:
  path: '/elevator_search'
  defaults:
    _controller: 'Drupal\elevator_search\Controller\EvelatorController::content'
    _title: 'Hello world'
  requirements:
    _permission: 'access content'

```

The `/modules/elevator_search/src/Controller/ElevatorController.php`:

```
<?php
/**
@file
Contains \Drupal\elevator_search\Controller\ElevatorController.
 */

namespace Drupal\elevator_search\Controller;

use Drupal\Core\Controller\ControllerBase;

class EvelatorController extends ControllerBase {
  public function content() {
      return array(
          //'#type' => 'markup',
          '#markup' => t('Hello world'),
        );
  }
};

```

It did show up under /admin/modules:

But when I try to install it I get an error:

> ReflectionException: Class Drupal\elevator\_search\Controller\EvelatorController does not exist in ReflectionMethod-\>\__construct() (line 123 of core/lib/Drupal/Core/Entity/EntityResolverManager.php).

# Answer
> 6 votes
Your class' name is "EvelatorController", the name of the php file of the class is "ElevatorController.php" - it is just a spelling problem

---
Tags: 8
---


# Question
Title: Remove "he" from all the Hebrew node URLs
All the nodes of my Hebrew site using Drupal 8 have this problem: The URL of all the nodes of my Hebrew site are similar to htts://www.example.com/he/node/1, instead of https://www.example.com/node/1. The difference is that now URLs contain /he/, which I have never added.

It happens even when a node has its language set to *English* or *Not specified*.

What I tried is the following:

1. I changed all nodes written for English speaking audience from *Hebrew* to *English* and I flushed the cache. This didn't help: The URLs still contained */he/*.
2. I thought it could be caused by the *Alternative hreflang* module, but uninstalling it did not resolve the issue, even after flushing the cache.

# Answer
> 1 votes
Deactive the URL detection method from /admin/config/regional/language/detection.

# Answer
> 1 votes
If you have translations, you should not turn off the URL detection method. Instead, you should change the domain prefix in the language settings for Hebrew to have no domain prefix.

---
Tags: 8, i18n-l10n
---


# Question
Title: Disable field validation of custom line items when cart is modified
How to disable custom line item's field validation when line item is removed from cart?

My line item has a required field and if product/line item is removed from cart it still tries to validate it. This causes form errors which isn't required.

# Answer
You need to search for this function (since your not giving full information about that custom module you have)

```
function nameOfModule_form_validate(&$form_state, &$form_id){

```

You can search inside that function where it is doing the validation
> 0 votes

---
Tags: forms, commerce
---


# Question
Title: Display Nodes from Taxonomy Category Term and Parent Terms
I am using Views and Drupal Commerce but not sure this should matter as all my products are also nodes. I have a taxonomy hierarchy for categories. Example

```
Exterior Accessories
|_ Top
   |_ Soft Tops
   |_ Hard Tops
|_ Bottoms
   |_ Right Bottoms
   |_ Left Bottoms

```

I can easily make a page that shows me the Hard Tops if on that location or Soft Tops if at that location. But is what i can not for the life of me figure out how to do is if I click on TOP I want to see Soft Tops and Hard Tops, and if I click on Exterior Accessories I want it to show products that are from any of the child elements with unlimited depth. So when viewing one of these pages it needs to work like so with the url.

categories/Tops -\> Would show soft tops and bottom tops categories/Soft-Tops -\> would show soft tops only categories/External-Accessories -\> Should show everything

# Answer
There is a function called `taxonomy_get_tree()` that you can use to fetch all the term IDs under a given parent ID. You can then call `taxonomy_select_nodes()` with an array of term IDs, which will return all nids that match that collection of tids.
> 0 votes

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


title: How to implement one click upload?

text:
# Question
Title: How to implement one click upload?
Drupal 8 supports multiple file upload, however the native interface requires three steps:

1. Select one or more files
2. Click Upload
3. Click Save

Ideally this could be simplified to a single step i.e. select one of more files, once done it uploads them. The user can delete a file later if they wish, but no point showing them the list of which they just select, just to make them change their mind.

**How should one click upload for multiple files be implement in Drupal?**

In pure PHP this can be done easily as follows (but Drupal 8 adds too many constraints for this to work):

```
<html>
<body>
<?php

$upload_dir = '/tmp/upload_test';
if ( ! is_dir( $upload_dir ) )
{
    mkdir( $upload_dir, 0777, true );
}

/** Rearrange the "parallel" _FILES array into consolidated file items. */
function rearrange( $arr )
{
    foreach( $arr as $key => $all )
    {
        foreach( $all as $i => $val )
        {
            $new[$i][$key] = $val;
        }
    }
    return $new;
}

if ( ! empty( $_FILES['data_fs_uploads'] ) )
{
    $files = rearrange( $_FILES['data_fs_uploads'] );
    print '<p>Copying uploaded files...</p>';
    foreach ( $files as &$file )
    {
        // File has 'name', mime 'type', 'tmp_name' path, 'error', and 'size'.
        $file['ext'] = pathinfo( $file['name'], PATHINFO_EXTENSION );
        $target_file = $upload_dir . '/' . $file['name'];
        if ( move_uploaded_file( $file["tmp_name"], $target_file ) )
        {
            print '<p>Copied ' . $file['name'] . '</p>';
        }
        else
        {
            print '<p>FAILED to copy ' . $file['name'] . '</p>';
        }
    }
}
?>

<form action="upload.php" method="post" enctype="multipart/form-data">
    <input id="data_fs_uploads" type="file" name="data_fs_uploads[]" multiple="multiple" onchange="javascript:this.form.submit();" />
</form>

<?php
foreach ( glob("$upload_dir/*") as $file )
{
    print '<div>' . $file . '</div>';
}
?>

</body>
</html>

```

# Answer
> 1 votes
Here is how you would create an auto save after selecting an upload file(s) in D8.

**upload\_autosave.libraries.yml**

```
auto:
  version: 1.0
  js:
    js/auto.js: {}
  dependencies:
      - core/jquery

```

**upload\_autosave.module**

```
/**
 * Implements hook_form_alter().
 * Adds JS file to all forms
 */
function upload_autosave_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
    $form['#attached']['library'][] = 'upload_autosave/auto';
}

```

**/js/auto.js**

```
(function ($) {
  Drupal.behaviors.upload_autosave = {
    attach: function (context, settings) {
    if ($('.image-widget-data').length || $('.field--type-file').length){
      $('.js-hide.button.js-form-submit.form-submit').remove();
      $('form', context).on('change', 'input.form-file', function() {
        $('#edit-actions .button.js-form-submit.form-submit')[0].click();
        $(".details-wrapper").html("<img src='/modules/upload_autosave/images/loading.gif'>");
        $('#edit-actions').fadeOut(1000);
      });
     }
    }
  };
})(jQuery);

```

---
Tags: 8, files
---


# Question
Title: Argument 1 must be an instance of Drupal\tcdev\Controller\UserAuth, instance of Drupal\user\UserAuth given
I want to programmatically log in a user with a custom controller. I want to pass my data with `$_POST` to the route (I pass data from a mobile application); if username and password are correct, the method/function should return `TRUE`.

The route is the following one.

```
tcdev.login:
  path: '/tclogin'
  defaults:
    _controller: 'Drupal\tcdev\Controller\MYCenterController::login'
    _title: 'Login call back'
  requirements:
    _permission: 'access content'

```

The code for the controller is the following one.

```
namespace  Drupal\tcdev\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\DependencyInjection\ContainerInterface;

class MyController extends ControllerBase {

    /**
     * \Drupal\user\UserAuth definition.
     *
     * @var \Drupal\user\UserAuth
     */
    protected $userAuth;

    /**
     * {@inheritdoc}
     */
    public function __construct(UserAuth $user_auth) {
        $this->userAuth = $user_auth;
    }

    /**
     * {@inheritdoc}
     */
    public static function create(ContainerInterface $container) {
        return new static($container->get('user.auth'));
    }
    }

    public function login() {
        $uid = $this->userAuth->authenticate($_POST['user'], $_POST['pass']);
        $acc = User::load($uid);

        //return new Response('Hi ' . $uid);
    }

}

```

It returns me the following error:

> TypeError: Argument 1 passed to `Drupal\tcdev\Controller\MyController::__construct()` must be an instance of `Drupal\tcdev\Controller\UserAuth`, instance of `Drupal\user\UserAuth` given, called in /Users/yms/Sites/devdesktop/gttc/modules/tcdev/src/Controller/MyController.php on line 32 in `Drupal\tcdev\Controller\MyController::__construct()` (line 23 of modules/tcdev/src/Controller/MyController.php)

Where is my mistake?

# Answer
> 1 votes
What is causing the *TypeError* you quoted is how you declare the arguments in the following method.

```
public function __construct(UserAuth $user_auth) {
  $this->userAuth = $user_auth;
}

```

Since you don't use any namespace for `UserAuth`, nor did you add `use \Drupal\user\UserAuth;` at the beginning of your code, PHP assumes the argument for the class constructor is an object of the `Drupal\tcdev\Controller\UserAuth` class because `Drupal\tcdev\Controller` is the namespace used from that file.
This is in conflict with the class of the object the constructor is actually receiving; that is why Drupal raises a `TypeError` exception.

Full-qualify the argument, or add the `use` line at the beginning of the file; either of them will fix the error.

# Answer
> 1 votes
Inject the user.auth in your controller:

```
$auth = $container->get('user.auth')

```

\[edited to clarify injection basics:

In public static function create(ContainerInterface $container) add $container-\>get('user.auth') to the return new static(...) statement.

In public function \__construct(...) add the $auth to the signature at the correct position. Then add a private (or protected) variable $auth to your controller and assign the value from \__construct to it.

You may simplify that by using drupal console or drush. They can create the boiler plate code for you.

If you don't want to use injection, you may use `$auth = \Drupal::service('user.auth');`

But this has drawbacks in testability.

\[end edit\]

then call the authenticate func:

```
$uid = $auth->authenticate($username, $pass);

```

With the $uid load the user:

```
$acc = User::load($uid);

```

Then set the user into the session:

```
  \Drupal::currentUser()->setAccount($acc);
  \Drupal::logger('user')->notice('Session opened for %name.', array('%name' => $acc->getUsername()));

```

Should work. But I don't think that it is a good idea to pass around the password in the URL of your tcdev.login...

Edit: Sample Code (generated by `drupal generate:controller`)

```
namespace Drupal\preosuser\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\user\UserAuth;

/**
 * Class AuthController.
 *
 * @package Drupal\preosuser\Controller
 */
class AuthController extends ControllerBase {

  /**
   * Drupal\user\UserAuth definition.
   *
   * @var \Drupal\user\UserAuth
   */
  protected $userAuth;

  /**
   * {@inheritdoc}
   */
  public function __construct(UserAuth $user_auth) {
    $this->userAuth = $user_auth;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('user.auth')
    );
  }

  /**
   * Checklogin.
   *
   * @return string
   *   Return Hello string.
   */
  public function CheckLogin($name) {
    return [
      '#type' => 'markup',
      '#markup' => $this->t('Implement method: CheckLogin with parameter(s): $name'),
    ];
  }

}

```

# Answer
> 1 votes
It seems you use mistake annotation and you have to pass right arguments to your constructor.

add `use Drupal\User\UserAuth;` and then try

```
/**
 * \Drupal\user\UserAuth definition.
 *
 * @var UserAuth
 */
protected $userAuth;

/**
 * Constructs .
 *
 * @param UserAuth $user_auth
 *
 */
public function __construct(UserAuth $user_auth) {
    $this->userAuth = $user_auth;
}

```

---
Tags: users, 8
---


title: How do I use custom user forms?

text:
# Question
Title: How do I use custom user forms?
After creating separate user registration form in *Structure \> Display Modes \> Form Mode* and creating those forms in *Configuration \> People \> Manage Forms*, how do I use these forms? I want different roles on my site to use different registration forms to register different users.

# Answer
There is no option for this in ui.

You have to define the display mode for the form in mymodule.routing.yml:

**Example from user.routing.yml**

```
user.admin_create:
  path: '/admin/people/create'
  defaults:
    _entity_form: 'user.register'
    _title: 'Add user'
  requirements:
    _permission: 'administer users'

```

In the line `_entity_form: 'user.register'` the form is `user` and the form mode is `register`.

Then you can access the form with the path defined here and restrict the access through roles with requirements.

**Edit (place the form on any page)**

If you want to place the form on any page, you need the form as a block.

You can use this module:

https://www.drupal.org/project/entityform\_block

But it does not have the option for arguments like form mode.

This experimental module can do this:

https://www.drupal.org/project/entity\_forms\_in\_blocks

> * Interesting features that does not exists for now with the other modules : ability to choose the form mode as Drupal 8 allows to (in Drupal 8, you can create additional form modes).
> 2 votes

---
Tags: forms, users, 8
---


# Question
Title: Retrospective fix to hook_update_n() in current release
I need to make a correction to a hook\_update\_N() function in the .install file which is causing SQL constraint errors when some users upgrade to the new release version. The original worked fine providing they ran update.php manually right after upgrading. But some users started using the site before running update.php and then when the did run it they get SQL errors. Also some automated upgrade scripts get the error. In both cases the required update is not performed.

Backgorund details are in issue https://www.drupal.org/node/2706119

The correction is done and ready, but I do not necessarily want to make another release, as it was only three months ago for the last release. 18k users have upgraded but 34k have not yet, so it would be good if the fixed update\_n() function could somehow be added into the current release. Is that possible? Can git tag the new commit into current version and then I re-release it again?

# Answer
Talking as project administrator on drupal.org, as far as I recall, you cannot create the same release twice; you need to create another release. You could delete the last release and recreate it, but I am not sure the Update manager module would notify users of a new release; if it did, I guess users would be confused about being notified of a new version that is the same they have.

If I understand correctly, the issue is that your update hook contained the following code.

```
   $rows_updated = db_update('role_permission')
     ->fields(array('permission' => 'schedule publishing of nodes'))
     ->condition('permission', 'schedule (un)publishing of nodes', '=') ->execute();

  return format_plural($rows_updated, '1 row updated in role_permission table.', '@count rows updated in role_permission table.');

```

Then, you changed it to the following one.

```
 // Updates done in two stages to avoid integrity constraint violation.
 // @see http://www.drupal.org/node/2706119

 // Select all role ids which already have the new permission value.
 $query = db_select('role_permission', 'rp')
   ->fields('rp', array('rid', 'permission'))
   ->condition('permission', 'schedule publishing of nodes');

 // Delete the rows for these roles which also have the old permission value,
 // as these are no longer needed and should not be updated to the new value.
 $rows_deleted = 0;
 if ($rows_to_delete = $query->execute()->fetchCol()) {
   $rows_deleted = db_delete('role_permission')
     ->condition('rid', $rows_to_delete, 'IN')
     ->condition('permission', 'schedule (un)publishing of nodes', '=')
     ->execute();
 }

 // Now update any other rows which still have the old permission value.
 $rows_updated = db_update('role_permission')
   ->fields(array('permission' => 'schedule publishing of nodes'))
   ->condition('permission', 'schedule (un)publishing of nodes', '=')
   ->execute();

 return format_plural($rows_deleted, '1 row deleted', '@count rows deleted')
   . ', ' . format_plural($rows_updated, '1 row updated', '@count rows updated')
   . ' ' . t('in role_permission table');

```

As I understand it, the new code is supposed to replace the old code, and your problem is that there are users who already run the update the update #7102. If that is the case, then I would rename `scheduler_update_7102()` (with the new code) `scheduler_update_7103()`. In this way:

* The users who didn't do the update will not run the old `scheduler_update_7102()` and they will not get the error
* The users who already ran `scheduler_update_7102()` will find `scheduler_update_7103()` which completes the update for them.
> 0 votes

# Answer
You can reset the status of the hook\_update\_n from below query `update system set schema_version=0 where name='modulename(hook)';`

Then you can run update.php so this hook\_update\_n() will work again with your latest changes.

Also you can see this link for schema\_version values `system_schema()` why we have to set schema\_version '0' instead of '-1'.

you can use following drush module for roll back the update version in the system table. Called "uroll" for update rollback.

https://github.com/danshumaker/drush-uroll

Usage: drush uroll --module=mycustommodule --version=5

This combined with a database backup reload script allows you to rinse and repeat when writing update functions
> 2 votes

---
Tags: updating
---


title: How do I change hashing algorithm?

text:
# Question
Title: How do I change hashing algorithm?
We are migrating a site to Drupal 8. The passwords are hashed with MD5, but Drupal 8 uses a different hashing algorithm.

Which file should I edit to change the hashing system to MD5?

We are aware of the risk, but it has been decided.

# Answer
> 6 votes
In Drupal 8.1+, password hashing and checking is managed by a service that can be replaced in your site's `services.yml` file. You need to provide your own implementation of `PasswordInterface`.

Instead of replacing the hash method, it would be safer for your implementation to inherit from `PhpassHashedPassword` and override the `check()` method to accept your MD5 hashes (but otherwise use the parent implementation). You can use a dedicated prefix to detect old hashes. And thanks to the `PhpassHashedPassword::needsRehash($hash)`, your password will be securely rehashed over time.

For instance, the following code expect you old hashes to be prefixed with `BAD$` in the database.

```
class MyPasswordService extends PhpassHashedPassword {
  function check ($password, $hash) {
    if (substr($hash, 0, 4) == 'BAD$') {
      // Migrate MD5 has
      $stored_hash = substr($hash, 4);
      $computed_hash = ... old and insecure hash code ...;
      return $computed_hash && Crypt::hashEquals($stored_hash, $computed_hash);
    }
    return parent::check($password, $hash);
  }
}

```

---
Tags: 8
---


title: How do I generate a HMAC code?

text:
# Question
Title: How do I generate a HMAC code?
How can I generate a HMAC code in Drupal 8?

In plain PHP, I would use `hash_hmac()`. Is there a more specific method/function, in Drupal 8?

# Answer
You could still `hash_hmac()` in Drupal 8. Drupal 8 has a static function that returns the HMAC given a couple of data and key arguments (`Drupal\Component\Utility\Crypt::hmacBase64()`). The differences are the following.

* `Crypt::hmacBase64()` returns the Base64-encoded HMAC value
* `Crypt::hmacBase64()` replaces some characters to make the string safe to use in URLs
* `Crypt::hmacBase64()` raises an exception when the arguments are not using the expected datatype

If you don't need to encode the HMAC value in Base64, or to pass the HMAC value in URLs, you can use `hash_hmac()`. You could consider `Drupal\Component\Utility\Crypt::hmacBase64()` a wrapper around two PHP functions, since its code is the following one.

```
if (!is_scalar($data) || !is_scalar($key)) {
  throw new \InvalidArgumentException('Both parameters passed to \Drupal\Component\Utility\Crypt::hmacBase64 must be scalar values.');
}

$hmac = base64_encode(hash_hmac('sha256', $data, $key, TRUE));
return str_replace(['+', '/', '='], ['-', '_', ''], $hmac);

```
> 4 votes

# Answer
It implemented in Drupal, How to Generate HMAC in drupal 7

Drupal 7

**Drupal 7** presents wrapper functions to get shorter, base-64 encoded hashes to use in URLs, etc. See:

```
drupal_hash_base64($data)
drupal_hmac_base64($data, $key)

```

**Drupal 8**

For Drupal 8 these have been moved to a utility class:

```
\Drupal\Component\Utility\Crypt::hashBase64($data)
\Drupal\Component\Utility\Crypt::hmacBase64($data, $key)

```

for more details follow this link
> 2 votes

---
Tags: 8
---


title: Passing arguments to drupal_get_form()

text:
# Question
Title: Passing arguments to drupal_get_form()
How can I pass arguments to `drupal_get_form()` in Drupal 7?

```
function new_menu_callback() {
  $vars = some_example_function(); // returns: array(1 => 'one', 2 => 'two');
  $output = $vars[2];
  $output .= drupal_render(drupal_get_form('new_form'));
}

function new_form($form, &$form_state) {
  // How can I access $vars[1] from new_menu_callback() here?
}

```

# Answer
> 35 votes
Just add `$vars` as second argument.

```
drupal_get_form('new_form', $vars);

```

and...

```
function new_form($form, &$form_state, $vars) {
// ...

```

Quote from drupal\_get\_form()

> ... Any additional arguments are passed on to the functions called by drupal\_get\_form(), including the unique form constructor function. For example, the node\_edit form requires that a node object is passed in here when it is called. These are available to implementations of hook\_form\_alter() and hook\_form\_FORM\_ID\_alter() as the array $form\_state\['build\_info'\]\['args'\].

# Answer
> 3 votes
The additional arguments you pass to `drupal_get_form()` are available in `$form_state['build_info']['args']`, but you can't have function calls in your `page arguments`. I'd suggest the following approach:

```
function mymodule_menu() {
    $items = array();
    $items['mymodule/example'] = array(
      'page callback' => 'drupal_get_form',
      'page arguments' => array('mymodule_form'),
    );
    return $items;
}

function mymodule_form($form, &$form_state) {
  // this function now uses dev/user friendly named keys
  $vars = mymodule_example_function();
  $form = array();

  $form['heading'] = array(
    '#markup' => check_plain($vars['heading']),
  );

  // use other arguments here

  return $form;
}

```

The rest of what you need is in the Form API reference

# Answer
> 1 votes
I had a similar issue and it was solved with a mix of @kalabro's answer and my own way to deal with it.

So basically I have a static landingpage where I use tokens. In the `hook_tokens` I call the register form via `$form = drupal_get_form('user_register_form', 'register-test');`.

And finally in the hook\_form\_alter I check the if the String is "register-test". This is done via `$form_state['build_info']['args'][0]`. Here the function:

```
function hook_form_user_register_form_alter(&$form, &$form_state, $form_id) {
...
if ($form_state['build_info']['args'][0] == 'register-test') {
    // manipulate the form as usual
    $form['...
  }
...
}

```

---
Tags: 7, forms
---


title: Display a message is not giving result?

text:
# Question
Title: Display a message is not giving result?
I like to show a message on 1 page of my website after login. Therefore I made a rule. To determine the mobile device I use module : mobile\_detect. I installed the corresponding library. Checking the status is saying it is available.

They module readme shows the example code:

```
$detect = mobile_detect_get_object();
$is_mobile = $detect->isMobile();

```

So when I rewrite this in a message with php eval like this:

```
#
<?php
$detect = mobile_detect_get_object();
$is_mobile = $detect->isMobile();
print ($is_mobile);
?>
#

```

So the result should be : #TRUE# or #FALSE# but I get back # #.

What can I do to solve this?

# Answer
> 1 votes
According to PHP manual

> A boolean **TRUE** value is converted to the string *"1"*. Boolean **FALSE** is converted to *""* (the empty string). This allows conversion back and forth between boolean and string values.

You can use below code instead

```
print ($is_mobile ? "TRUE" : "FALSE");

```

---
Tags: status-messages, mobile-tools
---


# Question
Title: Safe way to authentication users with REST
I can authentication and login user with below code in Jquery

```
$.ajax({
    url : "http://domain.com/user/login",
    type : 'post',
    data : 'form_id=user_login_form&name=' + encodeURIComponent("user") + '&pass=' + encodeURIComponent("password"),
    dataType : 'json',
    error : function(data) {
            //error code
    },
    success : function(data) {
      console.log(data);
        //success code
    }
});

```

But is seems this is not safe mode, and I think maybe someone can attack bruteforce to find users password.**I want to know is this method safe(I don't think so) and what is solution for make this safe against brute-force login attack.**

**This Ajax request don't return any Json output**,It seems try to login and if authorized then get `/user/uid`

**Note** "User login REST format" is similar, but it's not duplicate, and it doesn't have an accepted answer.

# Answer
> 1 votes
Probably because you're a header, should be like this:

```
{
    "_links": {
        "type": {
            "href": "https://yoursite.com/rest/type/node/article"
    }
  },
  "title": [{"value": "test title"}],
  "body": [{"value": "test body"}]
}

```

---
Tags: users, 8
---


title: Passwordless login in drupal 7

text:
# Question
Title: Passwordless login in drupal 7
If I use something like hybridauth, can I remove password field from Drupal completely? Or at the very least make it not required during registration?

# Answer
> 1 votes
Hybridauth does remove the need of password, so I probably can remove username and password fields from the user login forms through the hooks

---
Tags: 7, authentication-authorization
---


# Question
Title: Advagg css files are refering old site address
i have developed site in one machine (www.example.com). i moved all setup to another machine (www.example1.com).after moving some problem is there.some css files like "css\__48K1J5D3tG5zmBfajwIKY-4DGflacHFmJ6qlkBqjtPw\__hdw......css" under advagg\_css folder refering old site url.

# Answer
I think your site is trying to reference CSS that was held in your 'files' folder that may not now exist.

If you navigate to configuration \> Performance

and untick 'Aggregate and compress CSS files'

> Save Configuration
>
> Clear Caches.

Now check your site and see if it works. If it does you should be able to reenable the compression and hopefully your site will work fine.
> 1 votes

---
Tags: css-js-aggregation
---


# Question
Title: how to create path node/{some id}/add/{node_type} which loads node/add/{node_type} page
Create a path node/{some id}/add/{node\_type} which loads node/add/{node\_type} page form.

I want to get that { some id } to assign it default value in a form field client needed that url pattern as node/{some id}/add/{node\_type}.

# Answer
> 2 votes
We can achieve this by creating route as below.

cust\_group.route\_name: path: '/node/{group\_id}/add/{node\_type}' defaults: \_controller: '\Drupal\cust\_group\Controller\CustNodeController:add' requirements: \_permission: 'access content' ( change permission according to your requirement)

And create a CustNodeController controller with method.

```
/**
 * Returns responses for Node routes.
 */
class CustNodeController extends ControllerBase {

  /**
   * Provides the node submission form.
   *
   * @param \Drupal\node\NodeTypeInterface $node_type
   *   The node type entity for the node.
   *
   * @return array
   *   A node submission form.
   */
  public function add($group_id, NodeTypeInterface $node_type) {
    $group_id =

    $node = $this->entityManager()->getStorage('node')->create(array(
      'type' => $node_type->id(),
    ));

    $form = $this->entityFormBuilder()->getForm($node);

    return $form;
  }

}

```

make sure that {some id} != {node}.

---
Tags: nodes
---


# Question
Title: Gmap cluster different marker types seperatly
I created a Gmap with the Gmap module and views. There are two different marker types, based on different Gmap marker fields in the used node types.

The markers are clustered with GMaps Utility Library MarkerClusterer. And I added a MarkerClusterer styles in JSON. This results in clustering all markers regardless the marker type.

How to get each marker type cluster separately?

Is this something for OpenLayers?

# Answer
The Comparison of mapping modules includes this:

> GMap is considered a legacy module.

So maybe you want to have a look at the IP Geolocation Views & Maps module. Partial quote from its project page:

> Despite what the name may suggest, IP Geolocation Views & Maps (IPGV&M) is first and foremost a mapping engine.
>
> The module makes it very easy to create Views-based mapping solutions using the map renderer of your choice (**Google**, **OpenLayers** or **Leaflet**) with any location storage module of your choice, e.g.:

> This allows you to bring together modules and feature sets that without IPGV&M you would not be able to combine.
>
> Like beautiful animated marker clustering on Google or Bing or Mapbox ... any of various map providers.
>
> But more importantly IPGV&M adds some features you won't find as conveniently packaged elsewhere.
>
> These include marker differentiation based on field values or ranges (2nd screenshot) with or without font icons, various centering options, super-imposing the current visitor's location, allowing multiple content types to be displayed on the same map, full screen button and mini-map inset (bottom screenshot), polygon support (Geofield), marker tags and tool tips and cross-highlighting of associated content on the page when markers are hovered (and vice versa).

Head over to its (impressive) project page for even more information about it (it would be way too long to include a quote of it all here). That project page also includes various screenshots.
> 1 votes

---
Tags: 7, google-maps, javascript
---


# Question
Title: Postfix server and Simplenews module interaction
I send newsletters from my Drupal-7 website to all its registered users, using Simplenews module. As this number grows, I want to be able to track the number of successful and unsuccessful sends.
In my site, there is a postfix server installed, whose logs may give me a hint on how many mails were not delivered.
Although, the log file is a chaotic file -300.000 rows or even more- and the mails might be about something else, like registration for example.
I want to be able to track better how many of the newsletters were successfully delivered, in integration with my postfix server.
Or if you can suggest a better way to achieve that.
Thanks a lot!

# Answer
You could try to add a \[Reply-To:\] header to your mails. Maybe your postfix will send the non-delivery notifications to this address.
> 0 votes

---
Tags: 7, emails
---


# Question
Title: Utility or command to clean the database from anything left from a contributed/custom module
Is there a utility or command to clean the database from anything left from a contributed/custom module which has been installed and successively uninstalled?

# Answer
I don't think that this is possible because the core can not know what you need before you have it configured (fields, nodetypes etc).

You would need kind of a transaction checkpoint at the DB structure, and the possibility to rollback every structure manipulation and data therein that has happened after that point.

I usually have a system besides of my content staging system to test contributed modules. Copy content stage to dev, apply module on dev, test, rollback or move the module to content stage.

If you are the module dev yourself - make up your correct uninstalls :-)
> 3 votes

---
Tags: 8, database
---


# Question
Title: How to implement javascript to the theme Bootstrap
Please help me figure out what I'm doing wrong. I spent a lot of time to search for solutions, but could not find it. I am trying to add functionality Demo in the sub-theme Bootstrap. Added script to theme **subtheme/js/script.js**

```
(function ($, Drupal, window, document, undefined) {
    $(document).ready(function(){
        $(".b-left-side__pointer").click(function(){
           if ($(".switch").hasClass('b-container__left-side')) {
                $(".switch").removeClass('b-container__left-side').addClass('b-container-block-left');
            } else {$(".switch").removeClass('b-container-block-left').addClass('b-container__left-side');
                }
        });
    });
})(jQuery, Drupal, this, this.document);

```

Added styles to theme **subtheme/css/subtheme\_style.css**

```
.b-container__left-side {
  position: absolute;
  top: 52px;
  left: -300px;
  height: calc(100% - 52px);
  height: -moz-calc(100% - 52px);
  width: 300px;
  z-index: 1006;
  display: block;
  -webkit-transition-duration: 0.8s;
  -moz-transition-duration: 0.8s;
  -o-transition-duration: 0.8s;
  transition-duration: 0.8s;
}

.b-container-block-left {
  width: 300px;
  float: left;
  height: 97vh;
  margin-top: 0;
  border: none;
  background: #fff;
}

.b-left-side {
  height: 100%;
  overflow: auto;
}

.b-left-side__pointer:hover {
  cursor: pointer;
}

.b-left-side__pointer {
  position: absolute;
  bottom: 20px;
  left: 300px;
  width: 25px;
  height: 90px;
  border-bottom-right-radius: 3px;
  border-top-right-radius: 3px;
  background-color: #fff;
  box-shadow: 0 1px 5px rgba(0, 0, 0, 0.65);
  z-index: -1;
}

.b-left-side__pointer p {
  transform: rotate(-90deg);
  transform-origin: left top 0;
  -webkit-transform: rotate(-90deg);
  -webkit-transform-origin: left top 0;
  margin: 80px 0 0 0;
  font-family: WWF;
  font-size: 16px;
  letter-spacing: 1px;
  text-transform: uppercase;
}

```

Added to the end of the subtheme file **subtheme/templates/page.tpl.php** (the file is copied from a folder of Bootstrap theme themes/bootstrap/templates/system/page.tpl.php)

```
<?php if (!empty($page['l_sidebar'])): ?><!-- /#Left sidebar -->
    <div class="switch b-container__left-side">
      <div class="b-left-side">
        <?php print render($page['l_sidebar']); ?>
      </div>
      <div id="b-left-side__pointer" class="b-left-side__pointer">
        <p>Block</p>
      </div>
    </div>
<?php endif; ?>

```

Add to subthemes info file the following lines:

```
regions[l_sidebar] = 'Left sidebar'
stylesheets[all][] = css/subtheme_style.css
scripts[] = js/script.js

```

The subject area "Block" appeared but it does not respond on clicking.

# Answer
Please set z-index to solve it.

```
.b-left-side__pointer {
  z-index: 1;
}

```

Also, I have some advices for your code.

1. make use of Drupal behaviors instead of `$(document).read()`
2. use `jQuery.once()` to prevent event binding multiple times, it would happen if your page contains ajax.
3. use `jQuery.toggleClass()` to simplify the complexity of logic.

```
(function ($, Drupal, window, document, undefined) {
    Drupal.behaviors.sub_theme = {
        attach: function(context, settings) {
            $(".b-container__left-side", context).once('b-left-side', function() {
                $(".b-left-side__pointer", this).click(function(){
                    $(this).toggleClass('show');
                });
            });
        }
    }

})(jQuery, Drupal, this, this.document);

```

You need to change your CSS and also class name on HTML. I can't give opinion with that due to lack of information of your requirement.
> 0 votes

---
Tags: theming, javascript
---


# Question
Title: Exist a Drush command to update all the contents?
We have a client who was adding content to a separated dev server, the dev server is whitelisted only and doesn't allow incoming/outgoing connections to a lot of services.

The client was adding videos with the video embed field module, which automatically generates a static file on our server.

The firewall config means that this error was produced

```
Warning: file_put_contents(temporary://fileTjnJTX): failed to open stream:      "DrupalTemporaryStreamWrapper::stream_open" call failed in      file_unmanaged_save_data() (line 1898 of /var/www/user/includes/file.inc).
The file could not be created.

```

When editing and saving the content drupal tries to regenerate the image if none is available Our sysadmin is working the firewall configuration to allow the connections, but we was wondering if there is any easy way/drush commands/mysql statment to update all content,

# Answer
You can take a look inside the module Drush Entity because in this module you have the command `entity-update`:

```
drush @drupal.d7 entity-update node 53 --fields=title

```

If you want to improve the command to work in all nodes you can read this post:

How to adapt the name of a custom Drush command?

**EDIT:**

If you want to learn about Drush alias (@drupal.d7) you can go to: Drush Aliases: What, Why and How
> 3 votes

# Answer
Probably won't be a drush command for this but you can always create your own plugin for it since the actual code is fairly easy. Essentially what you want to do is to trigger 'node\_save()' for all items matching your criteria which should trigger whatever follow-on actions, rules, etc. are associated with that content. The range of options listed in this question for bulk delete give you a number of code snippets to use but this is the one I would use (modified for your specific case:

> Create a file with below code in root of drupal installation and execute the file.

```
<?php
  require_once './includes/bootstrap.inc';
  drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

  $aquery= db_query("SELECT nid FROM {node} AS n WHERE n.type = 'video'");
  while ($row = db_fetch_object($aquery)) {
    node_save($row->nid);
  }
?>

```

If you don't want to create php files, the Views Bulk Operations module offers a 'Node Save' action that can be just as simple.
> 1 votes

---
Tags: 7, drush, database, files
---


# Question
Title: How to change the view for a "Views: Filter by an entity reference view"-mode entity reference field on the node/add or edit form?
I have 2 content types: registration (R) and class (C). R has an entity reference field which is referencing to C using the "Views: Filter by an entity reference view" mode. The entity reference field must use the select list widget. User account also has an entity reference field field\_default\_class which is referencing to C. Because of business logic, the field\_default\_class's value never exists in the entity reference view's filtered result which is used in the R node.

Now if an authenticated user adds or edits a node of R, I need to check if current user's field\_default\_class is set or not. If set, I need to pragmatically set the R's entity reference nodes' select list to the user's field\_default\_class's value, then disable the select list for disallowing user to change the value.

I guess it's difficult to set a select list's option value which is not in the view's filtered results. Or maybe my codes as below have errors. But I don't know where is wrong :-(

```
/**
 * Implements hook_form_alter().
 */
function sisucustom_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'registration_node_form') {
    global $user;
    $account = user_load($user->uid);
    if (isset($account->field_default_class['und'][0]['target_id'])) {
      $entity_node = node_load($account->field_default_class['und'][0]['target_id']);
      $options = array($entity_node->nid => $entity_node->title);
      $form['field_register_for_class'][LANGUAGE_NONE][0]['target_id']['#options'] = $options;
      $form['field_register_for_class'][LANGUAGE_NONE][0]['target_id']['#default_value'] = $entity_node->nid;
      $form['field_register_for_class']['LANGUAGE_NONE']['#attributes']['#disabled'] = TRUE;
    }
  }
}

```

Or, is it possible to change the associated view to the entity reference field in node R? Because I can create another entity reference view which filters out only the one C which equals the current user's field\_default\_class's value. If it is, how to do it (in which hook)?

PS: I heavily use conditional fields module in node R. So maybe there are some pits against my goal. How to avoid those?

# Answer
My code is wrong, now it works as below:

```
/**
 * Implements hook_form_alter().
 */
function sisucustom_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'registration_node_form') {
    global $user;
    $account = user_load($user->uid);
    if (isset($account->field_default_class['und'][0]['target_id'])) {
      $entity_node = node_load($account->field_default_class['und'][0]['target_id']);
      $options = array($entity_node->nid => $entity_node->title);
      $form['field_register_for_class'] = array(
        '#type' => 'select',
        '#options' => $options,
      );
    }
  }
}

```

Finally I searched out a thread answering my question about modifying the widget info here.
> 0 votes

---
Tags: views, entities
---


# Question
Title: Can I use AddressBook values to populate a webform field?
I am currently trying to make lots of things work together. I'll try to put it simple without annoying details.

I work on a lawyer's site with **drupal commerce** installed, as well as **AddressBook**, **Webform** and **FillPDF**.

Outside the commerce functionalities (selling legal templates), my client wants her users to share loads of necessary informations with her (about the case she needs to work on).
Among these information are… you guessed it: name and address.
These informations might be used (many times) in pdf generated from forms (like mandates etc.)

Do any of you know a way…
to pick an address already stored in AddressBook to re-use it in a WebForm, (let's say, *via* a token)?
---OR---
to fill The AddressBook values as well as user informations from data typed in a WebForm which I could grab later on (the other way round suits me fine).

The aim being to provide a unique place to register all the necessary infos, in order to keep the site super-simple for middle aged people.

# Answer
> 0 votes
I was able, lately, to use a list of existing profiles in a node field. As these profiles are entities, an **'entity reference' field** can do the job. But I can't offer the possibility to choose from a list of entities in a webform though.
Now, I get a token related to this newly created field but not to the current user.

# Answer
> 0 votes
Her is what I came up with, if some of you are interrested. Mistake spotters welcome…

```
  <?php
  /**
   * Implements hook_token_info().
   * @ http://fredparke.com/blog/create-your-own-tokens-drupal-7
   */
  function address_token_token_info() {
    $info = array();
    // Define a new token type.
    $info['types']['my_custom_tokens'] = array(
    'name' => t('My custom tokens'),
    'description' => t('A token type for my custom tokens.'),
      );
  // Define any new tokens.
    $info['tokens']['my_custom_tokens']['user_name_line'] = array(
    'name' => t('Current user\'s full name'),
    'description' => t('A token I use to display the full name.'),
  );
  $info['tokens']['my_custom_tokens']['user_thoroughfare'] = array(
    'name' => t('Current user\'s thoroughfare'),
    'description' => t('A token I use to display the thoroughfare.'),
  );
  $info['tokens']['my_custom_tokens']['user_postal_code'] = array(
    'name' => t('Current user\'s postal code'),
    'description' => t('A token I use to display the postal code.'),
  );
  $info['tokens']['my_custom_tokens']['user_locality'] = array(
    'name' => t('Current user\'s postal code'),
    'description' => t('A token I use to display the locality.'),
  );
  $info['tokens']['my_custom_tokens']['user_country'] = array(
    'name' => t('Current user\'s postal code'),
    'description' => t('A token I use to display the country.'),
  );
  $info['tokens']['my_custom_tokens']['user_billing-address'] = array(
    'name' => t('Current user\'s billing address'),
    'description' => t('A token I use to display the whole address.'),
  );
  return $info;
}

/**
 * Implements hook_tokens().
 */
function address_token_tokens($type, $tokens, array $data = array(), array $options = array()) {

/* Variables to use in foreach within the fonction
@ http://stackoverflow.com/questions/8506359/how-to-assign-foreach-loop-to-a-variable#8506477
Elements declared via AddressBook
@ http://drupal.stackexchange.com/questions/116453/how-to-get-default-drupal-commerce-billing-shipping-customer-profile-in-code#146244
@ https://www.drupal.org/node/1245956#comment-5593970
Nested arrays
@ http://www.w3schools.com/php/php_arrays_multi.asp
*/
global $user;
$default_pid=commerce_addressbook_get_default_profile_id($user->uid,'billing');
$profiles = commerce_customer_profile_load_multiple(array(), array('uid' => $user->uid));

$user_name_line = $profiles[$default_pid]->commerce_customer_address['und']['0']['name_line'];
$user_thoroughfare = $profiles[$default_pid]->commerce_customer_address['und']['0']['thoroughfare'];
$user_postal_code = $profiles[$default_pid]->commerce_customer_address['und']['0']['postal_code'];
$user_locality = $profiles[$default_pid]->commerce_customer_address['und']['0']['locality'];
$user_country = $profiles[$default_pid]->commerce_customer_address['und']['0']['country'];

  $replacements = array();

  if ($type == 'my_custom_tokens') {
    // Loop through the available tokens.
    foreach ($tokens as $name => $original) {
      // Find our custom tokens by name.
      switch ($name) {
        case 'user_name_line':
                    // Work out the value of our token.
                    $value = $user_name_line;
          // Give our token it's value!
          $replacements[$original] = $value;
          break;
        case 'user_thoroughfare':
                    // Work out the value of our token.
                    $value = $user_thoroughfare;
          // Give our token it's value!
          $replacements[$original] = $value;
          break;
        case 'user_postal_code':
                    // Work out the value of our token.
                    $value = $user_postal_code;
          // Give our token it's value!
          $replacements[$original] = $value;
          break;
        case 'user_locality':
                    // Work out the value of our token.
                    $value = $user_locality;
          // Give our token it's value!
          $replacements[$original] = $value;
          break;
        case 'user_country':
                    // Work out the value of our token.
                    $value = $user_country;
          // Give our token it's value!
          $replacements[$original] = $value;
          break;
                case 'user_billing-address':
          // Work out the value of our token.
          $value = $user_thoroughfare.'<br />'.$user_postal_code.'<br />'.$user_locality.'<br />'.$user_country;
          // Give our token it's value!
          $replacements[$original] = $value;
          break;
      }
    }
  }

  return $replacements;
}

```

---
Tags: webforms, tokens
---


# Question
Title: REST resource for specified content type
Drupal 8 has a REST resource for all content type "Content" and let us to specified settings for all of content type in `admin/config/services/rest/resource/entity%3Anode/edit` ,but is globally, I mean if let users post data to Content type, they can Post data to all of content types and(But what I need is I don't let them to do this), I didn't find any option to restrict to specified content type.

I also take a look at permission and RESTful Web Services permission is for "Access POST on Content resource" and there is not any option for content types individually.

I want to know how can achieve this that REST POST feature exists for specified content type(s) and for some content type GET exists and for some content type REST not allowed?

**Update**(more deatils about what I want)
**I want anonymous user can POST contenttype1 content with REST** , I give permission to anonymous user to create contenttype1 content, and Authentication providers`section I check`cookie`and`basic\_auth\` methods, but when try to post data with following code it told me authentication required (I ran this snippet in browser console )

```
(function($){

                    jQuery.ajax({
                        url: '/rest/session/token',
                        method: 'GET',
                        success: function (token, status, xhr) {
                            var postData = {}
                            postData.title = [{'value': 'My Basic Page'}];
                            postData.field_enroll_email = [{'value': 'zhilevan@gmail.com'}];
                            postData.type = 'enroll';
                            jQuery.ajax({
                                url: "/entity/node",
                                method: "POST",
                                data: JSON.stringify(postData),
                                headers: {"Accept": "application/json", "X-CSRF-Token": token, "Content-Type": "application/json"},
                                success: function (data, status, xhr) {
                                    console.log(data);
                                }
                            });
                        }
                    });
})(jQuery);

```

# Answer
> I mean if let users **post** data to Content type, they can Post data to all of my content types and I didn't find any option to restrict to specified content type.

Doesn't `/admin/people/permissions` stop them?

**Permission**

* Basic page: Create new content
* Article: Create new content

> and for some content type GET exists

Don't you have to create a views rest export first before data is available to GET?

You can restrict here by adding a filter of `type` to your view.
> 2 votes

---
Tags: 8
---


# Question
Title: How do I correctly inform the system about my module's new config?
I'm working on a module that already comes with a config file in mymodule/config/install/mymodule.settings.yml, and I'm working on a new feature that requires its own set of configuration in mymodule/config/install/mymodule.newfeature.yml.

I assume I need to put the following code in an update hook.

```
function mymodule_update_8003() {
  \Drupal::service('config.installer')->installDefaultConfig('module', 'mymodule');
}

```

But if I do this, will sites that have overridden my existing configuration (from mymodule.settings.yml) get hosed, or is there another way to tell Drupal about my new configuration?

# Answer
I think I found a strategy that is only slightly hackish to let Drupal know that your module has created a new config. This solution assumes that your new config is in a separate yml file in yourmodule/config/install but it should be adaptable to a situation where you are adding a new config to an existing file....

```
/**
 * Install new config.
 */
function your_module_update_8003() {
  // Get all current configs for Your Module.
  $existing_settings_config = \Drupal::configFactory()->getEditable('your_module.settings');
  $existing_foo_config = \Drupal::configFactory()->getEditable('your_module.foo');
  $existing_bar_config = \Drupal::configFactory()->getEditable('your_module.bar');

  // Install the new configuration
  // (a new file was added a your_module/config/install/your_module.baz.yml)
  \Drupal::service('config.installer')
    ->installDefaultConfig('module', 'your_module');

  // Reset the existing configs in case they were changed when installing the
  // new configuration.
  $existing_settings_config->save();
  $existing_foo_config->save();
  $existing_bar_config->save();
}

```

It's not ideal, but it seems to work.
> 1 votes

# Answer
"will sites that have overridden my existing configuration (from mymodule.settings.yml) get hosed" Have you tried this?

A) I would suggest, to do separate configuration files (as granular as your updates need to be) and address them and update them separately, not using the "installDefaultConfig" method.

B) Have only one file, however in the updatehook don't call the config installer, but write the updateHook with "entityDefinitionUpdateManager" or any other service, custom php code you need.

On the other hand I totally agree: module default/update configuration system is really foggy.
> 0 votes

---
Tags: 8, configuration, updating
---


# Question
Title: How to use Rules to auto populate field B with the value of field A after saving a new node or updating an existing one?
This must be easy, but I just can't figure it out ...

My scenario is like so:

* I have a content type with **field A** (`title_field` \- text field) (that contains the title) and **field B** (`field_tagged_as` taxonomy reference).
* I need to auto populate **field B** with the value from **field A**, after saving a new node or updating an existing node.

Is there a way to do this using the Rules module?

# Answer
Here is a rule (in Rules export format) that does exactly what your question is about:

```
{ "rules_auto_populate_fields" : {
    "LABEL" : "Auto populate fields",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_presave" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "title_field" } },
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_tagged_as" } }
    ],
    "DO" : [
      { "data_set" : {
          "data" : [ "node:field-tagged-as" ],
          "value" : "[node:title-field]"
        }
      }
    ]
  }
}

```

Notice the "entity has field" conditions, for both fields. Those conditions will make the fields available in the Rules Action ... (so that you can reference field A and set the value of field B).

If you have the Rules UI enabled, and if the machine names of your fields are indeed "`title_field`" (for field A) and "`field_tagged_as`" (for field B), you should be able to just import this rule in your own site. If you're using other machine names, just adapt the machine names prior to importing this rule (and apply similar changes in the fields mentioned in the Rules Action).
> 0 votes

---
Tags: 7, rules
---


# Question
Title: Where is menu settings for node types stored in database
I looked in all tables to see where Drupal stores menu settings (including which menus should be available to a content type) for node types, but can't find it anywhere. We have a lot of content types on a multi site instance, and we're trying to enable menu for a content type directly in the database.

Thanks!

# Answer
That data is in a number of different variables in the `variable` table.

Specifically for menu options, you'll find it in a var named `menu_options_CONTENT_TYPE` (e.g. `menu_options_article` for an "article" type). For the menu parent it's `menu_parent_article`, and so on.

Above assumes Drupal 7, it'll be different for 8.
> 0 votes

---
Tags: database
---


title: Working with data from a form

text:
# Question
Title: Working with data from a form
I am trying to create a module with a simple form. The form allows the user to enter their address, from there I need to take the user's address, make a geocoding request, then send the data to another api, and then I need to display the data from the api request. The part I am having issues with is taking the submitted address so I can do the requests with it. How do I take the data from the form so I can use it? I do not need or want to save the data into my database.

Thanks in advance.

# Answer
In the form submit handler, look in the form state. The `values` array will contain submitted values.

So for a form element, 'foo', generated like this:

```
$form['foo'] = [
  '#type' => 'textfield',
  '#title' => t('Foo'),
];

```

You get the value like this:

```
function MYMODULE_form_submit($form, &$form_state) {
  $value_of_foo_field = $form_state['values']['foo'];
}

```
> 1 votes

---
Tags: forms
---


# Question
Title: How do call the template for a module block
My goal is create a custom block that uses a twig template that you can pass info to via the theme function like so.

```
  public function build() {
    return array(
      '#type' => 'markup',
      '#markup' => $this->siteContent(),
    );
  }

  public function siteContent() {

    $source_text = some_function_returning_html_from_user();

    return array(
      '#theme' => 'scadfashblock',
      '#source_text' => $source_text,
    );
  }

```

I got the above code from a tutorial trying to render a template file for a custom page. The problem is this code throws an error saying that an *array can't be returned this way, it must be a string*.

I even tried doing it the drupal 7 way...

```
  public function build() {
    return array(
      '#type' => 'markup',
      '#markup' => $this->siteContent(),
    );
  }

  private function siteContent() {

    $output = array();
    $output['source_text'] = some_function_returning_html_from_user();

    return theme('scadfashblock', $output);
  }

```

This throws an error:

> Call to undefined function `Drupal\<module>\Plugin\Block\theme()`

# Answer
> 5 votes
The `markup` render `#type` takes a string for its `#markup` element property, not a render array. However you do not need to wrap your custom theme/template with the markup type.

```
  public function build() {
    return array(
      '#theme' => 'scadfashblock',
      '#source_text' => $this->siteContent(),
    );
  }

  public function siteContent() {
    return some_function_returning_html_from_user();
  }

```

Then implement `scadfashblock` in hook\_theme, provide a `template_preprocess_scadfashblock` and a `templates/scadfashblock.html.twig` with your markup.

# Answer
> 2 votes
First you implement Hook\_theme like in D7

```
function preosasde_theme($existing, $type, $theme, $path) {
  return array(
      'similar_readings' => array(
          'variables' => array('readings' => NULL),
      )
  );
}

```

Then you create a render array that specifies the theme and the necessary variables as build() of your block:

```
foreach ($similar as $id => $data) {
      $sims[] = array('title' => $data['title'],
          'modified' => $data['date'], 'url' => $library->getAsdeUrl($id));
    }
return ['#theme' => 'similar_readings', '#readings' => $sims];

```

And finally you define a template in your module (or theme)

/templates/similar-readings.html.twig:

```
<table class='table table-striped table-condensed'>
                <tr><th>Datum</th><th>Titel</th></tr>
            {% if readings|length > 0 %}
              {% for artikel in readings %}
                <tr>
                        <td>{{ artikel.modified|date("d.m.Y") }}</td>
                        <td><a href="/{{ artikel.url }}">{{ artikel.title }}</a></td>
                </tr>
              {% endfor %}
            {% else %}
                <tr><td colspan="2"><em>keine</em></td></tr>
            {% endif %}
 </table>

```

You don't need the hook\_preprocess anymore. But don't forget to clear the cache!

# Answer
> 2 votes
You are getting *Call to undefined function `Drupal\<module>\Plugin\Block\theme()`* simply because you are using `theme()` without qualifying it with its namespace; since that code is in a file using a namespace, PHP things you are using a function in the same namespace. If Drupal still had `theme()` as function, in that file you should call it as `\theme()`, but since that function doesn't exist in Drupal 8, you need to change the code you are using.

Calling a theme function is not different from what you would do in Drupal 7 when using a render array.

```
  public function build() {
    return [
      '#theme' => 'scadfashblock',
      '#source_text' => $this->siteContent(),
    );
  }

  private function siteContent() {
    // Add your code to populate source_text.
  }

```

See also theme() renamed to \_theme() and should not be called directly, where it is explained that Drupal 8 modules should not use `theme()`.

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


# Question
Title: How to use hook_url_outbound_alter for emails only?
I have a Rule set up that sends a mail to a certain user with a link to a certain node. This link is altered using `hook_url_outbound_alter` to include additional details.

The problem is that hook\_url\_outbound\_alter also alters the URL everywhere else. Closing an overlay on the node view page rewrites the URL, clearing the cache (admin toolbar + devel) on the node pages rewrites the URL and so on.

I already attempted to check for an absolute URL in `$options`, but that does not solve the problems above.

```
function mymodule_url_outbound_alter(&$path, &$options, $original_path) {
  if (preg_match('|^node/([0-9]*)|', $path, $matches) && $options['absolute'] {
      $options['query']['parameter'] = $foo;
    }
  }
}

```

Can I use `hook_url_outbound_alter()` to only alter URLs when it was invoked from a specific module or something?

# Answer
> 1 votes
> Can I use `hook_url_outbound_alter()` to only alter URLs when it was invoked from a specific module or something?

You cannot, if that module doesn't put in `$options` (the same argument passed to `url()`) something that makes you understand that. To make an example, `entity_uri()` uses `$options['entity_type']` and `$options['entity']`; if you were trying to intercept the calls to `url()` done from `entity_uri()`, you could check the presence of those options.
Otherwise, the context given to `hook_url_outbound_alter()` doesn't allow to understand which module called `url()`. Maybe you could get that using debugging functions, but I am not sure I would put that kind of code in a module.

Since you seem to trying to alter links in an email sent from Drupal, you could implement `hook_mail_alter()`, assuming the emails are sent using the correct way of sending them with Drupal.

---
Tags: uri
---


# Question
Title: Render commerce item page with views - how to get proper add to cart form?
I use Drupal Commerce module to build my store. There are items in this store with sets of attributes such a color, size etc. I've created a content type to render a product. When I use a built in way to render this content type I have an interactive add to cart form with select lists or radio buttons for all attributes which loads values such a photo etc depend on it's values. Please suggest an approach how can I get this form using views?

I guess it should be quite a common task.

# Answer
> 0 votes
Create a View of your content.

Add field "Commerce Product: Add to Cart Form" to your View.

---
Tags: views, commerce
---


title: How do I manipulate votes on a node?

text:
# Question
Title: How do I manipulate votes on a node?
I have nodes that I want people to be able to vote on. I am currently using the Rate module for this. My use case also requires me to be able to change vote values on individual nodes if necessary. Please how would I do this?

I do not want to go into the database directly. The end user needs to be able to do this in the Drupal interface. I would also like to be able to restrict to access to this feature to certain roles using the permissions system

# Answer
# Undo/Cancel in individual vote

Head over to relative path `/admin/structure/rate`, and use the ***edit*** link for the rate widget for which you want to be able to Undo/Cancel a vote.

Next, within `/admin/structure/rate/id/edit` (with `id` corresponding to the widget you selected), scroll down to the section titled "***Interaction***". There you'll be able to change the value for "***Should a second click on the same button delete the vote?***" from "*No*" to "*Yes*". Save your changes, and repeat for each of the rating widgets for which you want to enable this facility.

# Set or delete votes for selected roles

There doesn't seem to be a Drupal interface for this. However, you may want to use the Services Voting API, which provide Services endpoints (actions) for Voting API module. From its project page:

> You are allowed to get votes as flexible as Voting API allows it. You are allowed to set votes as flexible as Voting API allows it. You are allowed to delete votes.

From its README.txt:

> After enabling the module as usual...
>
> 1. Go to admin/people/permissions
> 2. Enable the following permissions for your desired user role(s):
>     * Retrieve votes
>     * Set votes
>     * Delete votes
> 3. Go to admin/structure/services
> 4. Click 'edit' next to your endpoint
> 5. Enable the following resources under the 'votingapi' service:
>     * select\_votes
>     * set\_votes
>     * delete\_votes

And the issue about How to use this services resources? contains an interesting (JSON) samples about how to actually **set votes\***.
> 0 votes

---
Tags: rating
---


# Question
Title: How to make users get points when using Rate module to rate content?
I'm using the Rate module to allow the visitors to rate content. I need the author of the contents get point based in the votes provided for the rate module.

There are plenty of modules to allow the author to get points but I'm looking for one which works fine with the Rate module.

# Answer
> 0 votes
You should try the Voting Rules module. It works with voting\_api, the rate module uses voting\_api too, so it should solve your problem. Unfortunately not so well maintained module, so at least this patch need. But you can try it without patch, if it won't work, it will not because of that patch.

# Answer
> 1 votes
You can try User Points module.

> This module provides an API for users to gain or lose points for performing certain actions on your site.

# Answer
> 0 votes
To award (user) points based on the votes provided by the Rate module, you should use a combination of these often used modules to add (or subtract) user points when some node is voted up (or down):

It's also the approach used in the Answers module (disclosure: I'm a co-maintainer of it), i.e. within its submodule "Answers Userpoints", which also uses the Rate module). If you agree, read on ... (it only requires 4 custom rules if you have the above modules in place, no custom coding needed).

# Required Rules

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

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

Below are the required rules, for each of these cases (use the Rules UI to import them in your own site, after you enabled the required modules mentioned above). These rules use a content type with machine name `answers_question` (adapt this name to fit your own machine name).

Have a close look at how user points are added (or subtracted), and also who gains (or looses) those points. Obviously, the actual amounts of userpoints can be adapted in those rules to fit your own needs (note: if you don't want to "charge" a downvoter for downvoting, then simply ignore the Rules Actions related to user `vote:user`).

### Upvote a node

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

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

```

### Cancel the upvote a node

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

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

```

### Downvote a node

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

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

```

### Cancel the downvote a node

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

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

```

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


# Question
Title: Why user's rights has that impact on my Views pages?
I have two custom entities (Adhérents and Personnes) linked to each other and to User.

* One 'Adhérent' is mainly a "family" and has these fields: label, adresse (postal address), Téléphone (landline phone number), date d'adhésion (Membership start date).
* One 'Personne' is a "person" ;-) and has these fields: Nom (Lastname), Prénom (Firstname), Portable (Cellphone number).

Each 'Personne' is linked to one 'Adhérent'. One 'Adhérent' may be linked to many 'Personne' (one of these 'Personne' being the 'contact'). Each 'Personne' is linked to one 'User'.

'Personne' is defined as entity\_reference for 'Adhérent' (as the 'Contact'):

```
$fields['contactid'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('Contact'))
  ->setSetting('target_type', 'association_personne')

```

'Adhérent' is defined as entity\_reference for 'Personne':

```
$fields['adherentid'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('Adhérent'))
  ->setSetting('target_type', 'association_adherent')

```

'User' is defined as entity\_reference for 'Personne':

```
$fields['userid'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('Utilisateur'))
  ->setRequired(TRUE)
  ->setSetting('target_type', 'user')

```

I use Views to publish all these contents (see Screen captures below).

When I look at the output with a user with no specific rights (i.e. not Administrator), some of the data are not displayed:

1. In the 'Adhérents' view, the Contact column is empty (see capture 2) while there is a link to the entity (see capture 1).
2. In the 'Personnes' view, the link to the entity\_reference 'Adhérents' is there but the link to 'User' that should display email address (see capture 3) is completely absent, the column header is not even there (see capture 4).

Any idea?

The Permissions as they are set:

# Answer
> 1 votes
I'm not sure if I understand your problem correctly but would say that if it works as planned for admin user then the issue is with permissions.

Check permissions like: view user profile, view \[entity type\] etc.

---
Tags: views, 8, entities
---


# Question
Title: Is it possible to pass a Field value Via URL when creating a Node?
This may be posted elsewhere but I was having trouble finding anything answering my question directly.

I have a content type called Ticket that I want to have different fields based on what page a user is on when they push the button to create new ticket.

I am doing this because I would like a grand overview of all tickets entered, but there is different information needed from the user based on what queue they are entering a ticket for.

If there is a better way to do this I am open to suggestions.

Thanks in advance

# Answer
**For passing values to forms:**

There is a Drupal Module called Prepopulate which allows you to prefill fields on node forms using $\_REQUEST variables.

It is quite simple to use and merely requires you to rewrite the links to contain the field values you want to pass along. If you want to fill `field_your_field`on your ticket node, the link would need to look like this:

```
http://www.example.com/node/add/ticket?edit[field_your_field]=desired field value

```

---

That said, this wont hide any fields on the form, merely provide default values for them. If you want tickets with different fields, you could always use multiple node types.

---

If you want to actually hide fields based on the url, you could reuse the node form on custom pages and manipulate their fields there as you need.

You will need menu entries for your different node displays to distinguish which node form you want to call.

```
function ticket_module_menu() {
  $items['ticket/add/tech-ticket'] = array(
    'page callback' => 'drupal_get_form',
    'page arguments' => array('ticket_module_tech_ticket'),
    'access callback' => 'create ticket content', //or put a custom permission
  );

  $items['ticket/add/support-ticket'] = array(
    'page callback' => 'drupal_get_form',
    'page arguments' => array('ticket_module_support_ticket'),
    'access callback' => 'create ticket content', //or put a custom permission
  );

  return $items;
}

```

And then create a form for each entry:

```
function ticket_module_tech_ticket() {
  module_load_include('inc', 'node', 'node.pages');

  //get node add form for node type ticket
  $form = node_add('ticket');

  //Hide fields you do not want to display
  $form['field_your_field1']['#access'] = 0;
  $form['field_your_field1']['und'][0]['value']['#disabled'] = TRUE;

  return $form;
}

function ticket_module_support_ticket() {
  module_load_include('inc', 'node', 'node.pages');

  //get node add form for node type ticket
  $form = node_add('ticket');

  //Hide fields you do not want to display
  $form['field_your_field2']['#access'] = 0;
  $form['field_your_field2']['und'][0]['value']['#disabled'] = TRUE;

  return $form;
}

```
> 2 votes

---
Tags: nodes, uri
---