# Question
Title: Is it possible to login to Drupal with a custom user field, instead of username/pass?
I have two websites - One of them is Drupal 7, and the other is a different site (Site #2). In Site #2, within the user tables, is a field called "customid". Each user on Site #2 has a unique, randomly generated 30 character alphanumeric string within their respective "customid" field.

I can pull the value of the "customid" field for the user on Site #2, and use it as an input value in a form post to the Drupal 7 site.

In the Drupal 7 site, I created a custom user field "customid" as well.

Is it possible to make a form post from Site #2 to Drupal 7 - with the "customid" value as an input, and if it matches the "customid" field in the Drupal user table, log them in, else - redirect to the registration page?

We're essentially bypassing the username/password to log them in - I'm trying to log them in via custom user field.

I searched everywhere, and just couldn't find anything where something like this had been discussed. Thanks anyone for your time and help!

**UPDATE:**
I've tried implementing W.M.'s solution below, however upon attempting to enable the module, I get the white screen of death. Nothing shows up in the logs for the error.

For my custom module, I have two files:
ra\_login.module
ra\_login.info

**Info file:**

```
name = RA Login
description = Check ID and Login if there is a match, else go to Registration Page.
core = 7.x

; Information added by Drupal.org packaging script on 2013-12-16
version = "7.x-1.0"
core = "7.x"
project = "ra_login"
datestamp = "1387203506"

```

**Module File:**

```
<?php

function ra_login_menu()
{
    $items['authenticate-by'] = array( // or any other custom path you choose
        'title' => 'Login by SSO',
        'access callback' => true, // no point in authenticating at this point in code execution
        'page callback' => 'ra_login_function',
        'type' => MENU_CALLBACK,
        );
    return $items;
}

function ra_login_function($CONTACTID)
{
    // post the data to /authenticate-by as json with a parameter / property named CONTACTID holding the CONTACTID
    $postData = file_get_contents('php://input');

    $Data = json_decode($postData);

    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'user')
        ->propertyCondition('uid', 1, '<>')
        // User number 1 should not be able to log in using this method
        ->fieldCondition('field_contactid', 'value', $Data->CONTACTID, '=')
        ->range(0,1);

    $result = $query->execute();

    if (isset($result['user'])) {
        $uid = array_keys($result['user'])[0];
        $account = user_load($uid);
        global $user;
        $user->uid = $uid;
        $user->name = $account->name;
        $user->timezone = $account->timezone;
        user_login_finalize(); // Log user in
        drupal_goto('/user'); // or any other path to redirect logged in users to
    } else {
        drupal_goto('/user/register');
    }

}

```

Again, for some reason when I try to enable the module, I get a white screen. Thanks for anyone who can help!
**UPDATE:**
I turned on errors in php.ini - now instead of the white screen, it shows me the following error:

```
Parse error: syntax error, unexpected '[' in C:\inetpub\wwwroot\sites\all\modules\ra_login\ra_login.module on line 31

```

Line 31 is:

```
$uid = array_keys($result['user'])[0];

```

Any help is greatly appreciated!

# Answer
```
function YOUR_MODULE_page_build(&$page) {
  if(isset($_POST['customid'])){
    $customid=$_POST['customid']; //get your id
    $uid=get_uid_based_on_customid($customid);//you function to identify if someone has customid that customid
    if(empty($uid)){
        //if uid not found send user to login
        drupal_goto('/user');
    }else{
        //if uid found load user, authenticat it and redirect to page
        global $user; //global because is same var as the one drupal uses
        $user = user_load($uid);//set used data for you and drupal
        $login_array = array('name' => $user->name);
        user_login_finalize($login_array);//key function, will record user sessions
        drupal_set_message(t('User loged in!'));
        drupal_goto('/');
    }
  }
}

function get_uid_based_on_customid($customid){

  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'user')
  //->propertyCondition('uid', 1, '<>')
  // User number 1 should not be able to log in using this method because he is always admin, pay attention and uncomment when you go to prod
  ->fieldCondition('field_customid', 'value', $customid, '=')
  ->range(0,1);

  $result = $query->execute();

  if(!empty($result)){
    $data=$result['user'];
    reset($data);
    $first_element=current($data);
    $uid = $first_element->uid;

    return $uid;
  }else{
    return '';
  }

}

```
> 0 votes

# Answer
This is the code you need. In the Drupal site create the following module:

**Update:**

```
function my_special_login_menu()
{
    $items['authinticate-by-customerid'] = array( // or any other custom path you choose
        'title' => 'Login by customerid',
        'access callback' => true, // no point in authenticating at this point in code execution
        'page callback' => 'my_special_login_function',
        'type' => MENU_CALLBACK,
        );
    return $items;
}

function my_special_login_function($customerid)
{
    // post the data to /authinticate-by-customerid as json with a parameter / property named customerid holding the customerid
    $postData = file_get_contents('php://input');

    $Data = json_decode($postData);

    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'user')
        ->propertyCondition('uid', 1, '<>')
        // User number 1 should not be able to log in using this method
        ->fieldCondition('field_customerid', 'value', $Data->customerid, '=')
        ->range(0,1);

    $result = $query->execute();

    if (isset($result['user'])) {
        $uid = array_keys($result['user'])[0];
        $account = user_load($uid);
        global $user;
        $user->uid = $uid;
        $user->name = $account->name;
        $user->timezone = $account->timezone;
        user_login_finalize(); // Log user in
        drupal_goto('/user'); // or any other path to redirect logged in users to
    } else {
        drupal_goto('/user/register');
    }

}

```

For this code to work you need Entity API module and you should serve the site over SSL in order to encrypt the data transferred between the two sites.
> 1 votes

# Answer
I have no exact solution for your problem, but get idea how to deal with this,

By implementing following algorithm you can achieve.

* Requirement

-In Drupal Site you are saving "customid" this id is refer to "Site #2".
-When you store this "customid" in drupal database you need to update password field also and store this "customid" in password field by **drupal encryption format.**

---

* Now how to login by "customid"
-From site#2 you are sending "customid" to drupal site, write custom module to catch this customid in to drupal site.
-Now check this "customid" into drupal db and fetch user\_name of this related "customid".
-Now you have user\_name and password(customid), pass this to the drupal login form post function.
-Drupal will check user\_name and password if match user will log in.
> 0 votes

# Answer
Please review this contrib module: https://www.drupal.org/project/login\_custom\_field
> 0 votes

---
Tags: 7, users
---


title: Programmatically printing a block

text:
# Question
Title: Programmatically printing a block
So far I have been using this code, which works fine to print third-party module blocks.

```
<?php
    $block = module_invoke('views', 'block_view', 'og_members-block_1');
    print render($block);
?>

```

However, now I am trying to print a block that lives within my theme folder and I can't seem to figure out how to do that. How can I achieve this?

# Answer
> 13 votes
There is a way to programmatically print a block in a tpl file.

For 'module' defined blocks you can use `block_load()` see: block\_load op api.drupal.org

If you have a block defined through the block interface, it is called a custom block you can use `block_custom_block_get($bid)` see: block\_custom\_block\_get() on api.drupal.org

```
$block = block_custom_block_get(1);
$content = $block['body'];

```

# Answer
> 6 votes
You seem to be confusing things a bit.

Your method that you use in your code example is pretty sounds, it invokes `hook_block_view` for the desire module with a specific block delta. This method works fine because the only way to create blocks is through the hooks that the block module has defined.

This means that a theme can't create a block and you can't load a block from the theme. You would instead need to implement it in a module. Doing so would allow you to use the method you yourself has described.

# Answer
> 3 votes
It's work for me in Drupal 7.

```
$block = block_load('block', 'block_id');
$output =_block_get_renderable_array(_block_render_blocks(array($block)));
$res_output = drupal_render($res_output);
print render($res_output);

```

# Answer
> 1 votes
Programmatically printing a block in tpl file.

```
$view = views_get_view("block-name");
print $view->preview("block");

```

---
Tags: views, blocks
---


# Question
Title: Pass Webform Submission Back to Form Template
I'm trying to use a webform to accept data, do some processing and calculation, and pass it back to the user. For user-friendly purposes I don't want to redirect to a confirmation page, but back to the form page so they can enter the information again. So essentially, I want the form template to submit back to itself, and if it has received a submission, print out the results (for now). I'm having trouble finding a way to do this.

I have an override template (`webform-form-9.tpl.php`) in my theme folder and it is successfully overriding the default, however I can't find any **any** way to actually get the values the user just submitted - even printing **all** available variables doesn't display the submission. I can't even seem to check **if** the user submitted a form or not. Does the form template not even receive the submission data? That seems ***extremely*** peculiar if so, so I can only imagine I'm not just not getting it right.

Any advice here?

# Answer
> 0 votes
Just configure your webform, so the "redirect URL" is the following:

```
node/[node:id]/submission/[submission:id]

```

Now after submission you will see the result overview page of that submitted form

---
Tags: theming, webforms
---


title: Override Views RSS Feed Display

text:
# Question
Title: Override Views RSS Feed Display
I've been struggling with trying to create a custom xml REST API in D8 to replace a simple Views RSS feed (that is imported into other D7 sites using a custom Feeds importer) in a D6 site that's being migrated, and after pulling my hair out with the custom REST endpoint, I'm looking at doing what I did in D6, which is to create a Views RSS display. However, the feed requires some customization, so I need to determine how to add custom fields to the RSS feed. For other feeds in D7 sites, I've used the Views RSS module to add fields, but the D8 branch is still apparently not stable, so that does not seem to be an option.

To customize my RSS feed, I need to do two things:

1. Add custom elements (hook\_nodeapi($op = 'rss item') in D6)
2. Modify the query so only nodes with specified tids in a term reference field based on a views global null param passed in (hook\_views\_query\_alter() in D6)

So it appears that for an RSS Feed display in D8 views, the only fields displayed in the feed are the ones predefined in the row style settings (using Fields as the row type). With the Views RSS module not being available, is there a way with core Views to override the view to add custom fields (such as a class override)? I appears I can still use hook\_views\_query\_alter() to modify my query, but it doesn't do me much good if I can't add fields.

I could probably spend a few hours reading through code, but if anyone has a quick answer as to the best way to add custom elements to a D8 RSS display, or could point me in the right direction, I'd appreciate it.

Thanks.

# Answer
As documented here, I went with overriding the views row style plugin. All I did in the override was add the `render()` method and add my own modifications to the `$build` array to make it work.

```
<?php

namespace Drupal\video_export\Plugin\views\row;

use Drupal\views\Plugin\views\row\RssFields;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;

/**
 * Renders an RSS item based on fields.
 *
 * @ViewsRow(
 *   id = "mymodule_rss_fields",
 *   title = @Translation("Custom Fields"),
 *   help = @Translation("Display fields as RSS items."),
 *   theme = "views_view_row_rss",
 *   display_types = {"feed"}
 * )
 */
class MyModuleVRssFields extends RssFields {

  /**
   * Override of RssFields::render() with additional fields.
   *
   * @param object $row
   *
   * @return array
   */
  public function render($row) {
    $build = parent:: render();
    $item = $build['#row'];

    // Add MRCTV nid
    $item->elements[] = array(
      'key' => 'source-nid',
      'value' => $row->nid,
    );

    // Add channels and their target nids. We can get them from $row->_entity.
    $site = $this->view->args[0];
    // Get source nids from view.
    $channel_tids = array_column($row->_entity->field_channels->getValue(), 'target_id');
    // Now, get destination tids from config.
    $mapping_config = \Drupal::config('video_export.mappings');
    $all_mappings = $mapping_config->get('sites');

    foreach($channel_tids as $source_channel) {
      if(in_array($source_channel, array_keys($all_mappings[$site]['mappings']))) {
        $item->elements[] = array(
          'key' => $site . '-channel-map',
          'value' => $all_mappings[$site]['mappings'][$source_channel],
        );
      }
    }

    // Re-populate the $build array with the updated row.
    $build['#row'] = $item;

    return $build;
  }
}

```
> 1 votes

---
Tags: views, 8, feeds
---


# Question
Title: Can taxonomy tags/terms be more than one word?
I've created a view that filters content based on the tags I associate with each page. It works great when my tags are single words.

In this case, posts containing any one of the above tags appear on my page.

However, I want to create and select tags for posts that contain multiple words (e.g. movie titles) such as *Eternal Sunshine of the Spotless Mind*, *Garden State*, *The Aviator*.

Currently, I apply tags via checkboxes (in case that's relevant), not using the autocomplete.

When I do this, the views filter only displays content containing the FIRST tag. For example, Only content using the *Eternal Sunshine of the Spotless Mind* tag is displayed, but content containing the other two tags is absent.

Any idea why this might be? Are my tags just too long? If so, how can I get around this? The following are the contextual filter settings.

>

# Answer
> 2 votes
I found Only works with first taxonomy term views3 D7 which is about the same issue you have.

This is what comment #18 and #20 say. You might also look at comment #28.

> This works very well, but it only works with the first tag/taxonomy term applied to a node. For instance, if a post was tagged *Cheese*, *Recipe*, *Tomatoes*, and *Pasta*, it would show other posts tagged with *Cheese*, but not those tagged with *Recipe*, *Tomatoes*, or *Pasta*. Is there a way to get it to consider all taxonomy terms, not just the first one?

> I just tried this solution and it seems to work. Just select "Reduce Duplicates" then under "More" select "Allow multiple values." That's it, you should have all the things being printed out and not just things related to the first term. Let me know if this helps.

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


# Question
Title: Hide view when node's taxonomy value is empty
I have two taxonomy vocabularies: *departments* and *categories*.

I created a block view to display related pages (other pages in the same *department* **and** *category*) using contextual filter. All works well when a node has **both** *department* and *category* selected. But when I leave the *category* empty on a node, the view still shows other pages from the same *department*.

Is there any way to make the view not show up on the nodes with no *category*?

Here is what my contextual filter looks like:

# Answer
> 0 votes
With the help of my co-worker, we were able to make it work by adding two contextual filters: one for *category* and one for *department* taxonomy:

All other check boxes unchecked.

---
Tags: 8, views
---


# Question
Title: Switching out the autocomplete items in a user based entity reference
I'm working with an entity reference field in Drupal 8.3. It resides on a node and references users using the autocomplete widget. I have it setup to use an entity reference view for both what it is doing the lookup on and what it is showing. However no matter what modifications I seem to make to the view the auto complete always returns the referenced email address the new search criteria from the view is working ( it looks up the email by first or last name). Instead of the email however, I'm trying to instead show the users first name and last name as listed on the user entity.

I'm not sure if this is a bug in 8 as I remember this working in 7. Please let me know if there is anything I'm missing. If you need more info please just let me know. Thanks in advance for any help you can provide.

# Answer
In case anyone else stumbles on this... Its currently broken in 8.0x+ https://www.drupal.org/node/2174633
> 0 votes

---
Tags: 8, entities
---


# Question
Title: Giving users control of who sees their information?
On our rebuilt site we have an "about me" field attached to the user account. We want to give people the ability to specify who can see this information (or their whole user profile):

* Anyone (anonymous users)
* Authenticated users only
* paid Members of the organisation only (a role).

What's the best way of doing this?

# Answer
> 1 votes
Assuming that by "best" you mean that you want to avoid custom code if possible (e.g. because you don't have the skills and/or budget for that), then this is a way to make it work with zero custom code:

1. Implement your "About me" field as an entity reference, which references a node of some other content type (say "Details About Me"). So if somebody wants to complete such field, they should first have created an appropriate node of content type "Details About Me" (so that they can use that node in their entity reference field.
2. Add a special (required) field, which you define as a single value selection field, to let the user "*specify who can see this information*" (as in your question). Say you call such field "Visibility".
3. Whenever somebody wants to browse such "Details About Me" page, let the Rules module decide if such browse is yes or no allowed (based on the content type, and the value of that Visibility field. Refer to the answer to "How to make the permissions of a module more granular?" for a sample rule you could start from, and make it fit your case like so:

* Adapt the Rules Conditions.
    * Tune the redirect URL and message in the Rules Actions.

The above should take care of the "specify who can see this information"-part of your question. The remaining part of your question (= "or their whole user profile") is really a different question, not answered here. Though you could use a similar approach for that also.

---
Tags: users
---


# Question
Title: Entity reference, display custom field, not the title
I am using drupal 8.
I have two content types:

ORGANIZATION with the following fields
\- Title
\- image logo
\- much more fields

EVENT
\- Title
\- Start Date
\- End Date
\- Reference to the organizations (unlimited)

The event page needs to display the title of the event, start date, end date and all the logos of the organisations (not the titles of the organizations) How can I do this ?

In the "Manage Display" of the fields in the Event type, in the "Format" there are only 3 options, "Rendered Entity", "Entity ID", "Label". For "rendered entity" there are a few options as "Default", "Full content" and some other. But I cannot see an option to specify only to display the logo.

# Answer
Create a view and set the filter "Content: Type", to "one of"- Event and Organization. Pull all the fields you want to be displayed and publish the view in a page or as a block on any page. You can further customize the html of said created view per the instructions here :)
> 0 votes

---
Tags: entities
---


title: Not administrator - manage users

text:
# Question
Title: Not administrator - manage users
I have a user "manager". This user has the manager role but not the administrative role. Is it possible to allow this user to manage users and their roles? For example, if someone creates an account I want this user to be able to activate the account like an administrator can? And then to give a role to that user?

Or even change roles of existing user?

I have searched. But no luck.

Thanks in advance :)

# Answer
> 3 votes
Don't understand why Kevin's answer hasn't been accepted yet, here you go with a snip of the permissions that need to be enabled.

Have a look at this module- Administer Users by Role These are the new permissions that come with the module -

NEW PERMISSIONS 1 )Access the users overview page See the list of users at admin/people. Only users that can be edited are shown.

2) Create new users Create users, at admin/people/create.

3) Edit users with no custom roles Allows editing of any authenticated user that has no custom roles set.

4) Edit users with role XXX Allows editing of any authenticated user with the specified role. To edit a user with multiple roles, the sub-admin must have permission to edit ALL of those roles. ("Edit users with no custom roles" is NOT needed.)

-The permission for cancel work exactly the same as those for edit.

# Answer
> 1 votes
Have a look at the Role Delegation module. Some details from its project page:

> ... allows site administrators to grant specific roles the authority to assign selected roles to users, without them needing the administer permissions permission.
>
> For each role, Role Delegation provides a new assign ROLE role permission to allow the assignment of that role.
>
> The module also adds an assign all roles permission. Enabling this permission for a role is a convenient way to allow the assignment of any other role without having to check all the assign ROLE role permissions on the permissions page.

# Answer
> 0 votes
This role needs the "administer users" and "administer roles and permissions" permission to do this; plus all applicable permission to access the backend to get to the users overview page.

---
Tags: users
---


title: Use drush instead of vendor/bin/drush

text:
# Question
Title: Use drush instead of vendor/bin/drush
I try to get drush to run by calling just 'drush' and not 'vendor/bin/drush', I'm working with OSX Sierra. This doesn't work out as I want hope someone can help me with this.

When i follow the instructions here: http://docs.drush.org/en/master/install/

When at point 3: *If you want the convenience of calling drush instead of ../vendor/bin/drush, copy the examples/drush.wrapper file to your Drupal root and modify to taste.*

I get stuck. I copy the drush.wrapper file to my root and rename it to **drush** . Then I edit the path to:

```
cd "`dirname $0`"
vendor/bin/drush.launcher --local "$@"

```

Because I'm in the root I removed the **../** before vendor. When I save all I stil get:

> bash: drush: command not found

When I try going to: vendor/bin/drush.launcher it runs perfectly. What am I doing wrong?

# Answer
This isn't really a Drupal or Drush question, but a Bash/shell question: How to run a script in the current directory?

1. The script must be executable: `chmod u+x drush`
2. The script must be in the (executable) path. Since it's not recommended to have the current directory in the path (for very good security reasons), the solutions is to call Drush as `./drush` instead of just `drush`.
> 0 votes

---
Tags: drush
---


title: Return single value via AJAX

text:
# Question
Title: Return single value via AJAX
# Background

I have a Drupal 7 module that is making an AJAX call via `jQuery.ajax()` to a menu callback that I've defined in my module. The purpose isn't to return markup, but rather just a single string value.

This is all working as it should, but the method by which I'm passing the value back to jQuery seems messy to me.

I'm using:

```
// $condition is a simple string value.
print($condition);
drupal_exit();

```

# My Question

Is there a cleaner, more standardized way of doing this? This just feels hackish and messy to me.

Thanks, Drupalers!

# Answer
> 0 votes
That will work, but here is how I would do it (in D7). You can set up the ajax callback server side like this:

```
$response = array('value' => $condition);
drupal_json_output($response);
drupal_exit();

```

Then your value will be available as data.value in your success callback:

```
$.ajax({
  url:example.com/some/path
  success:function(data) {
    alert(data.value);
  }
});

```

---
Tags: ajax
---


# Question
Title: Views Data Export not showing data export display option in view
I installed Views Data Export module on a Drupal 7.50 site and it works beautifully. I am trying to incorporate it now into a new website (which happens to be 7.54). I have cleared all the Drupal caches as well as the browser cache and have checked that the module is enabled. I also have Views Excel Export extension installed and enabled on both sites.

I'm completely stumped that this works perfectly on one site and not working on another.. .

Update: I thought I checked the versions, as I installed them on the same day, but somehow, the one on the site that works is an older version (3.1 vs. 3.2).

I tried uninstalling it and installing the older version but it didn't resolve the issue. I also checked permissions but there aren't permissions for this module.

Here is the conversation on Drupal.org with no resolution.

# Answer
I had installed the Views Excel Export module *first*. I had to uninstall both modules and then reinstall them in the correct order: Views data export first and then Views Excel Export. This solved the issue for me!
> 2 votes

---
Tags: 7, views, importing-exporting
---


# Question
Title: Configuration Management is broken between two site environments, I have no idea how to fix it
I started working on a d8 site two weeks ago; there are two site environments: @dev and @staging, on different servers. I have been developing the site locally (adding views, pages etc.) and using the configuration exporter to export a compressed config file from @dev which I then import @staging. I occasionally use the single export/import tab to pass configuration upstream.

Mostly it's been working fine until recently. I somehow broke the site when I added a specific view. Now whenever I try to import into @staging i get the same error, regardless of *what* I'm importing:

> The configuration cannot be imported because it failed validation for the following reasons: Configuration views.view.view\_name depends on the module that will not be installed after import.

A while ago I created a module (using drupal console) with the purpose of inserting a block, but it failed (probably because I gave the module the same name as the theme I'm developing). I removed this module, but not before enabling it on one or more of the sites - it's the only thing I did that broke the site (prompting a restore from an earlier database version).

I just want to fix the configuration syncing between the two sites, because I can't go on re-configuring both versions of the site for each and every change. That's so D7.

I'd be happy to provide any other information needed to help diagnose/solve the issue. I use git to synchronise themes between the two files, filezilla to copy site files from @staging -\> @dev, drush to install any modules (eg. drush en ds) to @dev and git to transfer those changes to @staging. Occasionally I'll synchronise databases from @staging -\> @dev (because content entry - handled by another internal team - has begun).

# Answer
> 4 votes
Aaaaaargh! After banging my head against the wall I found the issue. I checked the yml output (either single export tab; the /sync folder; or in the compressed export file) and found the 'broken' line:

```
dependencies:
  config:
    - core.entity_view_mode.node.teaser
    - node.type.leistungen
  module:
    - null
    - node
    - user

```

I removed the '- null' entry and retried the import - it worked fine.

MegaDoh!

# Answer
> 0 votes
The Null module was developed as a workaround. From the module page:

> This module is used to get around a bug in CMI which outputs a 'null' dependency in CMI.

---
Tags: 8, configuration
---


# Question
Title: Push Notifications: How can I send extra parameters in push notification data?
I am using Push Notifications module to send notification to registered tokens.

I am able to send a plain text notification successfully via rules.

I am looking for a way to send the notification with extra fields so that it can be identified which type of notification is this and what action to take on this.

Below is the data example I need to send the notification in:

```
{
   "aps":{
      "alert": "Enter your message",
      "badge":1,
      "sound":"default",

     "extraField 1":"some value",
     "extraField2":"identifier"
   }
}

```

Here is the rule export:

```
    {
    "rules_push_notification" : {
    "LABEL" : "Push Notification",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "push_notifications" ],
    "ON" : { "node_insert" : [] },
    "IF" : [
      { "node_is_of_type" : {
          "node" : [ "node" ],
          "type" : { "value" : { "music" : "music", "news" : "news" } }
        }
      }
    ],
    "DO" : [
      { "push_notifications_send_message_bulk" : { "message" : "[node:title]", "target_group" : "authenticated" } }
    ]
  }
}

```

**Notes**:

* My Rules Action maps (corresponds) to the data example like so: that "Enter your message" would be replaced by the value of "`[node:title]`".
* About that "extra field 1" (and "extra field 2"): When I send a Push notification, *On Tap* it needs some action to be taken which is decided in those extra fields, for an example if I need to show a music article I will send "music" as identifier and second field will be the node id of the content help mobile to open that particular article.

# Answer
> 0 votes
Starting from the answer given by vgordiya, I was able to solve the problem.

I created my own custom module with `dependencies[] = push_notifications`.

In my rule, I have added the custom PHP code in action and passing code something like below.

```
$uids = array('1');
$message = array(
             'alert'=>'Enter your message',
             'badge'=>1,
             'sound'=>'default',
             'extraField1'=>'some value',
             'extraField2'=>'identifier'
           );
cusotm_module_send_message($uids,$message);

```

My custom module function I added is:

```
function cusotm_module_send_message($recipients, $message) {
    if (!is_array($recipients) || !is_array($message)) {
        return FALSE;
    }

    if (!module_exists('push_notifications')) {
        watchdog('cusotm_module', t('Push Notification Module not found'));
        return false;
    }

    // Shorten the message characters / 8 bit.
    $message = truncate_utf8($message, PUSH_NOTIFICATIONS_APNS_PAYLOAD_SIZE_LIMIT, TRUE, TRUE);

    // Convert the payload into the correct format for delivery.
    $payload = $message;

    // Determine if any of the recipients have one or multiple tokens stored.
    $tokens = array();
    foreach ($recipients as $uid) {
        $user_tokens = push_notification_get_user_tokens($uid);
        if (!empty($user_tokens)) {
          $tokens = array_merge($tokens, $user_tokens);
        }
    }

    // Stop right here if none of these users have any tokens.
    if (empty($tokens)) {
        return FALSE;
    }

    // Send a simple alert message.
    push_notifications_send_alert($tokens, $payload);
}

```

The reason behind doing it this way was to not changing the original module code so that the patch don't get vanished at the time of update.

# Answer
> 0 votes
The current D7 release of the Push Notifications module does not allow/support such *extra fields* (as in your question). However below are some suggestions to get you closer ...

### Integrate 'identifier' in your Alert message

You could produce 2 types of ***alert*** messages, based on the content type (= *News* or *Music*), by adapting your Rules Action. This by also integrating the available `[node:content-type]` token, it could look something like so:

```
      { "push_notifications_send_message_bulk" :
        { "message" : "[node:content-type] notification: [node:title]",
          "target_group" : "authenticated" } }

```

Using this approach, your message starts to look like a kind of transaction to be processed, for which there might be solutions to further process it on your target platform).

### Integrate 'some value' in your Alert message

Using a similar approach, you could further extend this to also include that "`some value`" related to your "`extraField 1`" (as in your question), probably you'd want to use the available `[node:nid]` token for that.

However, as per your comment (="it will appear `{1234 (nid)} / {music (node type)} / The title (The title of the node)` which does not looks good actually."), you may want to try another approach (as explained in the next suggestion).

### Send JSON messages

Your data example seems to be a variation of what's shown in the issue about "sending JSON messages", in which the notification message is a JSON string that looks like so:

```
{"title": "my title",
 "message": "my message",
 "additionalData": { "key": "value", ... }}

```

Comment #3 in that issue refers to the issue about "Custom Payloads for Push Notifications", and which includes a patch (current status = needs review) with which you might get it to work somehow.

### Upcoming improvements in D8

Help is on its way, as detailed in the D8 related issue about "Create content entity for push notifications".

# Answer
> 0 votes
I am already facing same problem before 2 years back. Which I resolved thrugh using of custom php code in rules action and passing code something like below.

```
$uids = array('1');
$message = array(
             'alert'=>'Enter your message',
             'badge'=>1,
             'sound'=>'default',
             'extraField1'=>'some value',
             'extraField2'=>'identifier'
           );
push_notifications_send_message($uids,$message);

```

and applying patch which is attached herewith. Patch is compose and uploaded just for your issue.

---
Tags: 7, rules, services, notifications
---


# Question
Title: How do I make a theme require Jquery (for anonymous users)?
I'm creating a theme for D8 called 'herchel'.I'm trying to get this theme to require jquery on all pages (D8 doesn't load Jquery for anonymous users by default)

Looking through the what little documentation i can find on d.o in addition to the core themes, I created a file called herchel.libraries.yml

I've tried the following... all with no luck:

```
drupal.herchel:
version: VERSION
  dependencies:
    - core/jquery

```

-

```
drupal:
version: VERSION
  dependencies:
    - core/jquery

```

-

```
herchel:
version: VERSION
  dependencies:
    - core/jquery

```

Does anyone have any ideas on what I need to put in this?

# Answer
> 11 votes
I ran in to this upgrading one of my contrib themes to Drupal 8 as I wanted jquery.once for anonymous users. Here is what I did which works great:

In *herchel.libraries.yml*

```
herchel-corescripts:
  version: VERSION
  js:
    js/scripts.js: {}
  dependencies:
    - core/jquery
    - core/drupal.ajax
    - core/drupal
    - core/drupalSettings
    - core/jquery.once

```

Then in your theme's *herchel.theme* file.

```
function herchel_preprocess_page(&$vars, $hook) {
  // Render the library as laid out in herchel.libraries.yml
  $libraries['#attached']['library'][] = 'herchel/herchel-corescripts';
  \Drupal::service('renderer')->renderRoot($libraries);
}

```

Pay mind to the indenting as well for the YML code. Though it's not really documented that well yet, you can have a look at this issue and its change log.

Replace hook\_library\_info() by \*.libraries.yml file

Note that you also see a theoretical theme's "scripts.js" file in the code above but you may not need it. In my theme, that's what uses jquery to call custom code.

This code is probably a good reference too for the YML bits. Note that in both cases `version` is at the same level as `dependencies`.

I also made a list of Drupal 8 issues I encountered and took part in with my D8 upgrade.

***Update:***

I've fixed the code, we ran in to this issue: Replace #attached library array values with provider-namespaced strings

Note this:

```
 $libraries['#attached']['library'][] = array('herchel', 'herchel-corescripts');

```

vs.this

```
$libraries['#attached']['library'][] = 'herchel/herchel-corescripts';

```

I tested and the errors went away. :)

# Answer
> 11 votes
In your theme create libraries file `herchel.libraries.yml`. Into this file put:

```
libname:
  version: 1.x
  js:
    js/scripts.js: {}
  css:
    theme:
      css/styles.css: {}
  dependencies:
    - core/jquery

```

In `herchel.info.yml` put:

```
libraries:
  - herchel/libname

```

# Answer
> 0 votes
Maybe you have add spaces before "dependencies:"

this is true:

```
google-maps:
  version: VERSION
  js:
    vendor/gmap3.js: {cope: footer}
    //maps.google.com/maps/api/js?key=000000: { type: external, cope: footer}
  dependencies:
    - core/jquery
    - core/drupal
    - core/drupalSettings

```

for example this is wrong:

```
google-maps:
  version: VERSION
  js:
    vendor/gmap3.js: {cope: footer}
    //maps.google.com/maps/api/js?key=000000: { type: external, cope: footer}
    dependencies:
      - core/jquery
      - core/drupal
      - core/drupalSettings

```

---
Tags: 8, javascript
---


# Question
Title: Using module_invoke for Menu causes Undefined index notice
I'm displaying a multi-level menu in the footer of my site using:

```
$block = module_invoke('menu', 'block_view', 'main-menu');
          print render($block['content']);

```

Which is displaying correctly, however I am receiving this warning message:

> Notice: Undefined index: main-menu in menu\_block\_view() (line 486 of /\****/modules/menu/menu.module).

Any suggestions on how to suppress this message?

# Answer
It is caused from the following line, executed from `menu_block_view()`.

```
$data['subject'] = check_plain($menus[$delta]);

```

$delta is the value you pass as last argument to `module_invoke()`.

It means there isn't any menu with that ID, or you misspelled the menu ID. Try with main\_menu, for example.
> 0 votes

---
Tags: blocks, navigation
---


# Question
Title: Cannot load module uninstall page - says module does not exist
I accidentally deleted the Markdown filter module from the file system while it was still enabled. So I installed it again, via the GUI.

Now I cannot load the module uninstall page - it says "The website encountered an unexpected error. Please try again later", and the message in the log says `Drupal\Component\Plugin\Exception\PluginNotFoundException: The "markdown" plugin does not exist. in Drupal\Core\Plugin\DefaultPluginManager->doGetDefinition()`

I have cleared caches, run cron, deleted `sites/default/files/php` ... all to no avail.

Any ideas?

Edit: I have just tried to enable the module again, and got this message: `Unable to install Markdown filter, markdown.settings already exists in active configuration.` I looked through the config and cache\_config tables and cannot find this setting.

# Answer
It turned out there **was** a `markdown.settings` entry in the database (in the `config` or `cache_config` table, I forget which). I deleted this row and then it was possible to install and then uninstall the module.
> 0 votes

---
Tags: 8, input-formats
---


# Question
Title: CKEditor tabber shows tabs to the right on the screen when logged in as admin
I have reported this question with the CKEditor tabber issues, but I thought I ask this question here too, in case I am missing something obviuos... I have installed the `CKEditor tabber` module and after creating some tabs and tab content, the tabs is pushed out to the right in the screen. Like this:

I noticed that when I log out the tabs appear above the content as expected. I have narrowed it down to the permission "Use admin toolbar". When the admin toolbar is shown, the CKEditor tabs is showed as on the image. When the admin toolbar is not shown, the CKEditor tabs shows as they should above the tab content.

I have spent hours trying to find how the toolbar affects the CSS in this way, but I can't figure out what to do...

Anyone?

UPDATE: I noticed that the "left" attribute is 100% too large in this section that is in charge of the first tab's positioning and width:

```
<dt id="tab-0-0" class="current style="width:16,6667%; left:100%;">

```

In the js file semantic-tabs.js this code is in charge of the above:

```
$(this).css({
  'width': (100 / numTabs) + '%',
  'left': (100 / numTabs * tabIndex) + '%'
});

```

So, if I add "`-100`" after `tabIndex` above the tabs are positioned correctly when logged in with the admin toolbar visible. If logged out the tabs are pushed to the left in this case. So the JS decides to add 100% to the "`left`" value when the toolbar is visible. Also I can see that for half a second the tabs are positioned correctly before being pushed out, every time I refresh the page. I am going crazy here...

# Answer
In case anyone else has the same problem I will answer my own question. I found the answer to my problem in this issue for the same module: https://www.drupal.org/node/2774763 The problem was not exactly the same to begin with, but the solution was the same. The variable tabIndex needed to be placed within the function, not outside as a global. Problem solved.
> 0 votes

---
Tags: 7, wysiwyg, toolbar
---


# Question
Title: Views UI affected due to multiple modules
jquery.once is perfectly working, I placed console.log inside it, but I still get this error especially when I load the Views UI without even before I press any button

When I press any button, a progress animation appears and again this error appears

```
views-admin.js?op2hqg:164 Uncaught TypeError: $form.once is not a function
    at Object.Drupal.behaviors.addItemForm.attach (views-admin.js?op2hqg:164)

```

When I investigates I found that the following jquery select returns 0 objects

```
var $form = $(context).find('form[id^="views-ui-add-item-form"]').first();

```

How to solve this, should I disable any modules?

# Answer
This might happen when you use jQuery Update, I faced the same and solved using CDN providers

Use jQuery CDN Provider in your jQuery Update Settings should solve this issue

Load your settings as yoursite.com/admin/config/development/jquery\_update, You will see the option **jQuery and jQuery UI CDN** with None in the dropdown list.

Choose **jQuery** and **Save Configuration**
> 1 votes

---
Tags: 7, views, javascript
---


# Question
Title: Default Breadcrumb is not working in bootstrap drupal 8?
I have rendered the breadcrumb in page.html.twig

```
{# Breadcrumbs #}
    {% if breadcrumb %}
      {% block breadcrumb %}
        {{ breadcrumb }}
      {% endblock %}
    {% endif %}

```

and default breadcrumb block is available in the block layout. And then I have assigned in the block in Highlighted region.

When I debugging the breadcrumb, its not working properly.

Please help me , how to sort out this issue?

# Answer
The twig code doesn't work and you don't need it for the breadcrumb block to be available in the block layout. It's the other way, first you assign the breadcrumb block in for example the Highlighted region. Then you print the region with the breadcrumbs in page.html.twig:

```
{{ page.highlighted }}

```

In D8 it's not possible to access the breadcrumbs in the page template directly. You have to use a Drupal block. See https://www.drupal.org/node/2410773.

BTW Twig Blocks are not connected to Drupal blocks. They are used to extend templates:

> Blocks are used for inheritance and act as placeholders and replacements at the same time. They are documented in detail in the documentation for the extends tag.
> 4 votes

---
Tags: 8, breadcrumbs
---


# Question
Title: Redirecting Drupal multisite non-www to www with varnish / nginx
I'm building Drupal multisite with 35 sites (~60 different domains) and I'd like to redirect non-www urls to www regardless of domain.

Nginx is redirecting all domains to Drupal install folder.

I've tried to redirect domains with Nginx without success (is that even possible because of varnish?)

I was able to redirect single domain with Varnish (something like "if domain == xxx then redirect to www.domain.tld"), but I don't want to make own redirect rule for every domain.

# Answer
> 1 votes
I was able to do it with the following nginx config:

```
if ($host !~* ^www\.) {
   rewrite ^(.*)$ http://www.$host$1 permanent;
}

```

# Answer
> 1 votes
```
vcl 4.0;

sub vcl_recv {
   if (req.http.host ~ "^([-0-9a-zA-Z]+)\.([a-zA-Z]+)$") {
   return (synth (750, ""));
   }
}

sub vcl_synth {
   if (resp.status == 750) {
   set resp.status = 301;
   set resp.http.Location = "http://www." + req.http.host + req.url;
   return(deliver);
   }
}

```

# Answer
> 0 votes
something like this from Varnish manuals will work:

```
sub vcl_recv {
    if (req.http.host ~ "^([-0-9a-zA-Z]+)\.([a-zA-Z]+)$") {
        error 750 regsub(req.http.host, "^([-0-9a-zA-Z]+)\.([a-zA-Z]+)$", "http:///www.\1.\2" + req.url);
    }

sub vcl_error {
    if (obj.status == 750) {
        set obj.http.Location = obj.response;
        set obj.status = 301;
        return(deliver);
    }
}

```

# Answer
> 0 votes
*Non www to www* redirections should be **handled by Varnish before requesting backend**, to avoid weird errors such as loops, no backend connection...

In `sub vcl_recv` (this is VCL 4 syntax) :

```
sub vcl_recv {
    #THIS IS THE IMPORTANT POINT
    #redirect non www to www domains ip no subdomain defined
    if (req.http.host ~ "^([-0-9a-zA-Z]+)\.([a-zA-Z]+)$") {
       return (synth (750, ""));
    }

    # Normalize the header, remove the port
    set req.http.host = regsub(req.http.host, ":[0-9]+", "");

    #OFTEN SHIPS WITH THIS OTHER ONE, COMMENT IT OTHERWISE IT WILL FAIL
    #set req.http.Host = regsub(req.http.Host, "^www\.", "");

    # For the sake of example, a couple of custom backends,
    # note www is specified in the req.http.host
    if (req.http.host ~ "foo.example.tld") {
         set req.backend_hint = example;
    }
     elseif (req.http.host ~ "www.other.com") {
         set req.backend_hint = other;
    }

```

In `sub vcl_synth`, add this :

```
if (resp.status == 750) {
    #redirect non www to www
    set resp.status = 301;
    set resp.http.Location = "http://www." + req.http.host + req.url;
    return(deliver);
}

```

Finally, in your vhosts, it is not necessary anymore to have two server blocks, you can comment or remove the non www one

```
#server {
#        listen 1.2.3.4:8080;
#        server_name example.tld;
#        return 301 http://www.example.tld;
#}

server {
        listen 1.2.3.4:8080;
        server_name www.example.tld;

```

---
Tags: redirection, multi-sites, proxies
---


title: How do I access the view block name?

text:
# Question
Title: How do I access the view block name?
How do I access the view block name?

```
function <theme_name>_theme_suggestions_views_view_alter(array &$suggestions, array $variables) {

 // print_r(array_keys($variables));
  if (isset($variables['view'])) {
    $view_id = $variables['view']->id();
    $view_block = 'testing';
    array_splice($suggestions, 1, 0, 'view__bundle__' . $view_id . '__' . $view_block);
  }
}

```

# Answer
> 1 votes
I'm not really sure this is correct, but I guess you are looking for the `id` for the block:

```
function THEMENAME_theme_suggestions_views_view_alter(array &$suggestions, array $variables) {
  if (isset($variables['view'])) {
    $view_id = $variables['view'];
    $id = $view->id();
    $block_id = $view->getDisplay()->display['id'];
    array_splice($suggestions, 1, 0, 'view__bundle__' . $view_id . '__' . $block_id);
  }
}

```

You can also print out the contents of the `$view->getDisplay()->display` array to check for other values that you might use.

---
Tags: theming, 8
---


# Question
Title: entityQuery array instead of orConditionGroup()
I'd written a query based on the "simplified" version here. And my code looked like this.

```
$results = \Drupal::entityQuery('node')
  ->condition('type', 'mytype')
  ->condition('status', 1)
  ->condition('field_first.target_id', $anArrayOfNids)
  ->condition('field_seciond.target_id', array($anotherNid))
  ->execute();

```

The code was working, I know it was. But now I'm getting an "SQLSTATE\[HY093\]: Invalid parameter number: number of bound variables does not match number of tokens" SQL error.

I tried replacing it with just array(540) and got the proper result. Then I gave it array(546) and got the different, expected response, but as soon as I put \[540,560\] or array(540,560), I get that error, instead of what i used to get, which was the combined results.

# Answer
> 2 votes
I don't know how it was working before, but the solution seems to be to place the explicit 'IN' in the query as such:

```
$results = \Drupal::entityQuery('node')
  ->condition('type', 'mytype')
  ->condition('status', 1)
  ->condition('field_first.target_id', $anArrayOfNids, 'IN')
  ->condition('field_seciond.target_id', array($anotherNid))
  ->execute();

```

Or, if I was to just convert this to the more complicated, yet more robust method:

```
$results = \Drupal::entityQuery('node');
$group = $query->orConditionGroup();
foreach($anArrayOfNids as $nid) {
  $group->condition(field_first.target_id, array($nid));
}
$query->condition('type', 'mytype')
  ->condition('status', 1)
  ->condition('field_seciond.target_id', array($anotherNid))
  ->condition($group)
  ->execute();

```

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


# Question
Title: Applied Image Styles Cause Failed Image Render
I'm using Aquia Dev on Windows 10 for a local installation and after the latest Drupal 8 update (8.2 to 8.3), applying image styles to content now causes my images to fail to render.

Checking debug and the directory, the paths `site/MY-SITE/files/styles/MY-STYLES` are correct and the images are there, but for whatever reason Drupal can't pull the images. The alt text is displayed instead. Image-styles that were applied to items before the update still render correctly, but changing the styles on the correctly rendering images thereafter again breaks them.

Most of the information I have found is geared toward changing "775" ownership on a Unix platform. I can't figure out what that means and translate it to a Windows set up.

# Answer
> 0 votes
These aren't private files, right? There is an open issue for something that sounds a lot like this. We applied patch #34 and it resolved the problem for us.

---
Tags: 8, media, theming
---


# Question
Title: How do I create a landing page that can go to page--front?
I have two pages, the intro page (page--intro.tpl.php) and the front page (page--front.tpl.php). When you type worldovercomers.church, the front page loads.

How can I set it so when the user visits the website the intro page loads instead (worldovercomers.church/intro)?

I also want to include a link that when clicked goes to the main site (page--front). How can this be achieved?

Please note that I'm a Drupal novice.

# Answer
> 0 votes
You should try the Panels module.

It has a "pages" feature that allows you to create pages from pre-existing layout templates that are included, or you can create and import your own layouts from .tpl files. Then you can dynamically add content to them (it stores the settings in the database, but you can use the Features module to store them in code).

---
Tags: redirection
---


# Question
Title: How do I make a custom form post to an external URL?
In Drupal 8, I want a form to post to another page, but when I change the action on `$form['#action']` to a URL that makes it post there, it skips the validation.

I need the code for posting to an external URL in a submission handler.

I tried this but it gives an error.

```
$response = new TrustedRedirectResponse('https://google.com');
$form_state->setResponse($response);

```

# Answer
You can post your information using the Drupal HTTP client (Guzzle):

```
$client = \Drupal::httpClient();
$request = $client->post($url, $post_data);
$response = json_decode($request->getBody());

```

Where $url is the URL you want to post to, and $post\_data is an array containing the data you want to post, in key =\> value format. You can build the key values in the submit handler of your form, getting the submitted values from $form\_state.

You can read more about it here: https://drupalize.me/blog/201512/speak-http-drupal-httpclient

You can build your post data something like this:

```
$post_data = [
  'field1' => $form_state->getValue('field1'),
  'field2' => $form_state->getValue('field2'),
  ...
]:

```
> 5 votes

# Answer
This worked for me

```
$url="https://jsonplaceholder.typicode.com/posts";
    $client = \Drupal::httpClient();
    $post_data = $form_state->cleanValues()->getValues();
    $response = $client->request('POST', $url, [
    'headers' => ['Content-Type' => 'application/x-www-form-urlencoded'],
    'form_params' => $post_data,
    'verify'=>false,
  ]);
    $body = $response->getBody()->getContents();
    $status = $response->getStatusCode();
    dsm($body);
    dsm($status);

```
> 0 votes

---
Tags: forms
---


title: Accessing a list of all node fields

text:
# Question
Title: Accessing a list of all node fields
Programmatically, in Drupal 8, how can I retrieve a list of all entity reference fields including label and machine name?

I have tried the entity manager service, but it only produces a list of keys without their label, and it is reported to be deprecated.

# Answer
If something is deprecated then that means there is always an explicitly documented replacement and a change record with code examples.

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

In this case it's the EntityFieldManager/entity\_field.manager service. But neither entity.manager nor entity\_field.manager provide just field names, both provide a list of field definitions.

As always, share your code and you get more specific answers.

One thing you need to be aware of in regards to labels is that there are field storages (fields in 7.x terms) and fields (field instances in 7.x). A single field storage (= unique field name) can exist on different bundles/node types with different names. So one approach to do what you want would be to start with the field map for your type, then loop over the bundles for each field to get the field definition and that label.
> 1 votes

---
Tags: 8, entities
---


# Question
Title: How to apply database updates once the module is installed and after a new entity has been created?
I have installed custom module.

Then created `entity: content type` with `drupal generate:entity:content`

Now, I'm trying to update the module, so that the entity is installed, but no clue.

Since code is looking for entity table, I cannot even uninstall the module.

I also checked in `http://domain.com/admin/modules/update` but says no update available.

I even tried changing module version in `.info.yml` but that seems not working.

What is the best way to let drupal know that my module needs update?

**UPDATE 1**

My `RewardNotification.php`

```
<?php

namespace Drupal\reward\Entity;

use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Field\BaseFieldDefinition;
use Drupal\Core\Entity\ContentEntityBase;
use Drupal\Core\Entity\EntityChangedTrait;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\user\UserInterface;

/**
 * Defines the Reward notification entity.
 *
 * @ingroup reward
 *
 * @ContentEntityType(
 *   id = "reward_notification",
 *   label = @Translation("Reward notification"),
 *   bundle_label = @Translation("Reward notification type"),
 *   handlers = {
 *     "view_builder" = "Drupal\Core\Entity\EntityViewBuilder",
 *     "list_builder" = "Drupal\reward\RewardNotificationListBuilder",
 *     "views_data" = "Drupal\reward\Entity\RewardNotificationViewsData",
 *
 *     "form" = {
 *       "default" = "Drupal\reward\Form\RewardNotificationForm",
 *       "add" = "Drupal\reward\Form\RewardNotificationForm",
 *       "edit" = "Drupal\reward\Form\RewardNotificationForm",
 *       "delete" = "Drupal\reward\Form\RewardNotificationDeleteForm",
 *     },
 *     "access" = "Drupal\reward\RewardNotificationAccessControlHandler",
 *     "route_provider" = {
 *       "html" = "Drupal\reward\RewardNotificationHtmlRouteProvider",
 *     },
 *   },
 *   base_table = "reward_notification",
 *   admin_permission = "administer reward notification entities",
 *   entity_keys = {
 *     "id" = "id",
 *     "bundle" = "type",
 *     "label" = "entity_type",
 *     "uuid" = "uuid",
 *     "uid" = "user_id",
 *     "read" = "read",
 *   },
 *   links = {
 *     "canonical" = "/admin/structure/reward_notification/{reward_notification}",
 *     "add-page" = "/admin/structure/reward_notification/add",
 *     "add-form" = "/admin/structure/reward_notification/add/{reward_notification_type}",
 *     "edit-form" = "/admin/structure/reward_notification/{reward_notification}/edit",
 *     "delete-form" = "/admin/structure/reward_notification/{reward_notification}/delete",
 *     "collection" = "/admin/structure/reward_notification",
 *   },
 *   bundle_entity_type = "reward_notification_type",
 *   field_ui_base_route = "entity.reward_notification_type.edit_form"
 * )
 */
class RewardNotification extends ContentEntityBase implements RewardNotificationInterface {

  use EntityChangedTrait;

  /**
   * {@inheritdoc}
   */
  public static function preCreate(EntityStorageInterface $storage_controller, array &$values) {
    parent::preCreate($storage_controller, $values);
    $values += array(
      'user_id' => \Drupal::currentUser()->id(),
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getType() {
    return $this->bundle();
  }

  /**
   * {@inheritdoc}
   */
  public function getEntityType() {
    return $this->get('entity_type')->value;
  }

  /**
   * {@inheritdoc}
   */
  public function setEntityType($entity_type) {
    $this->set('entity_type', $entity_type);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getEntityId() {
    return $this->get('entity_id')->value;
  }

  /**
   * {@inheritdoc}
   */
  public function setEntityId($entity_id) {
    $this->set('entity_id', $entity_id);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  function getValue() {
    return $this->get('value')->value;
  }

  /**
   * {@inheritdoc}
   */
  function setValue($value) {
    return $this->set('value', $value);
  }

  /**
   * {@inheritdoc}
   */
  public function getCreatedTime() {
    return $this->get('created')->value;
  }

  /**
   * {@inheritdoc}
   */
  public function setCreatedTime($timestamp) {
    $this->set('created', $timestamp);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getOwner() {
    return $this->get('user_id')->entity;
  }

  /**
   * {@inheritdoc}
   */
  public function getOwnerId() {
    return $this->get('user_id')->target_id;
  }

  /**
   * {@inheritdoc}
   */
  public function setOwnerId($uid) {
    $this->set('user_id', $uid);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function setOwner(UserInterface $account) {
    $this->set('user_id', $account->id());
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public function getRead() {
    return (bool) $this->getEntityKey('read');
  }

  /**
   * {@inheritdoc}
   */
  public function setRead($read) {
    $this->set('read', $read ? TRUE : FALSE);
    return $this;
  }

  /**
   * {@inheritdoc}
   */
  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
    $fields = parent::baseFieldDefinitions($entity_type);

    $fields['user_id'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Authored by'))
      ->setDescription(t('The user ID of author of the Reward notification entity.'))
      ->setRevisionable(TRUE)
      ->setSetting('target_type', 'user')
      ->setSetting('handler', 'default')
      ->setTranslatable(TRUE)
      ->setDisplayOptions('view', array(
        'label' => 'hidden',
        'type' => 'author',
        'weight' => 0,
      ))
      ->setDisplayOptions('form', array(
        'type' => 'entity_reference_autocomplete',
        'weight' => 5,
        'settings' => array(
          'match_operator' => 'CONTAINS',
          'size' => '60',
          'autocomplete_type' => 'tags',
          'placeholder' => '',
        ),
      ))
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

    $fields['uuid'] = BaseFieldDefinition::create('uuid')
      ->setLabel(t('UUID'))
      ->setDescription(t('The notification UUID.'))
      ->setReadOnly(TRUE);

    $fields['type'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Type'))
      ->setDescription(t('The notification type.'))
      ->setSetting('target_type', 'reward_notification_type')
      ->setReadOnly(TRUE);

    $fields['entity_type'] = BaseFieldDefinition::create('string')
      ->setLabel(t('Entity Type'))
      ->setDescription(t('The type from the notified entity.'))
      ->setDefaultValue('node')
      ->setSettings(array(
        'max_length' => 64
      ))
      ->setRequired(TRUE);

    $fields['entity_id'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Notified entity'))
      ->setDescription(t('The ID from the notified entity'))
      ->setDefaultValue(0)
      ->setRequired(TRUE);

    $fields['value'] = BaseFieldDefinition::create('float')
      ->setLabel(t('Value'))
      ->setDescription(t('The numeric value of the notification.'))
      ->setDefaultValue(0)
      ->setRequired(FALSE);

      $fields['read'] = BaseFieldDefinition::create('boolean')
          ->setLabel(t('Has user viewed notification'))
          ->setDescription(t('A boolean indicating whether the Notification is visited.'))
          ->setDefaultValue(FALSE);

    $fields['created'] = BaseFieldDefinition::create('created')
      ->setLabel(t('Created'))
      ->setDescription(t('The time that the entity was created.'));

    $fields['changed'] = BaseFieldDefinition::create('changed')
      ->setLabel(t('Changed'))
      ->setDescription(t('The time that the entity was last edited.'));

    return $fields;
  }

}

```

# Answer
> 2 votes
There are a few different ways to do this and since I'm not completely sure of your setup I'm listing all of them here for you but #3 below is probably what you want for your situation. There are so many ways to create entities now that I figured listing the different ways may help you or someone in the future.

1. This is probably not what you want but I'm adding it here because it's fairly easy to write simple updates with this method. I'm not entirely sure if I understand you correctly, but if you are trying to or need to run an update in a custom module, you need to have an update hook present with the needed updates for your module. So you can use `hook_update_N()`. It is a common Drupal task to have updates present in modules and if building custom modules for your application/site a good way to ensure changes are applied to each environment (Dev, Test, Prod, Local) as needed. `hook_update_N()` integrates with the update system and the 'N' represents the minor version changes, so that when the update command is ran, Drupal looks for these hooks and runs the version that it needs to run at that time. Usually you would start with `MODULENAME_update_8001()` or something similar and future changes you will increment the number each time and the update will be picked up each update command that is issued. So that will give you a basic reason primer in making basic updates, you can run just about any db updates this way but like I said, this is probably just extra information.
2. You could use the configuration system to make entity field changes and run config updates. This is a very basic way and will not be very usable for a module that needs to run on multiple sites.
3. If you are registering your entity in your module and you have your schema declared in src/Entity/ENTITYNAME.php this is the file that controls the schema and upon initial install of the module the tables are setup. If you enabled the module before you added your entity schema file fret not, you can use `drush updatedb --entity-updates` or `drupal update:entities` to get the new entity or any updates that you have made to the entity throughout development or while deploying changes. An example in the documentation can be found on Creating a content entity type in Drupal 8. Just read through that example and it will give you any other information you need regarding this issue.

Also, you said you created the entity. I'm guessing you did that through the command line, but you want to automate that task. I gave you a link that guides you in adding the entity information to your module in the third point. Specifically, look at the src/Entity/Contact.php section and you will need to have that present, then run the entity update command to register the entity. You may have to rebuild the cache during that process so that Drupal will register the new Entity Class. This is a basic entity manager task; once you do this, you will never go back to any other way. See also Entity Cheat Sheet.

# Answer
> 3 votes
You can use:

```
drush updatedb --entity-updates

```

> --entity-updates
>
> Run automatic entity schema updates at the end of any update hooks.

If you have changed any entity/field definitions in your custom module you can quickly apply this to update.

---
Tags: 8, entities, updating
---


# Question
Title: Finding all Basic Pages not referenced by a main-menu entry
I am trying to produce a list of all published English or no-language Basic Pages on my Drupal 7 website that are not in the main menu hierarchy.

Initially, I tried the technique in Finding all nodes not referenced by a menu entry or another node only to find that the suggested SQL command does not match the current Drupal 7 database structure for menus.

After downloading the Data Dictionary and some trial and error, I came up with the following drush command (with the environment replaced by \[redacted\]):

drush @\[redacted\] sqlq "SELECT nid, title FROM node WHERE node.type = 'page' AND node.status = 1 AND (node.language = 'und' OR node.language = 'en') AND CONCAT\_WS('node/', CAST(node.nid AS CHAR(6))) NOT IN (SELECT link\_path FROM menu\_links WHERE menu\_links.menu\_name = 'main-menu') ORDER BY nid"

Unfortunately, this command is returning all published English or no-language Basic Pages on my Drupal 7 website, not just those which are not in the main menu.

After testing some variations, I suspect that "CONCAT\_WS('node/', CAST(node.nid AS CHAR(6)))" is the problem but have no idea how to fix it. Replacing CONCAT\_WS with CONCAT does not help.

All Basic Pages on this website have 5 or 6 digits in their node ID. It is okay if I have to use a different statement to get all 5-digit node IDs and all 6-digit node IDs.

# Answer
I had to wrap the cast in a TRIM function:

drush @\[redacted\] sqlq "SELECT nid, title FROM node WHERE node.type = 'page' AND node.status = 1 AND (node.language = 'und' OR node.language = 'en') AND CONCAT('node/', TRIM(CAST(node.nid AS CHAR(7)))) NOT IN (SELECT link\_path FROM menu\_links WHERE menu\_links.menu\_name = 'main-menu') ORDER BY nid"
> 0 votes

---
Tags: database
---


title: How do I fund a project?

text:
# Question
Title: How do I fund a project?
I'm just trying to find out how to fund a Drupal project.

I found https://www.drupalfund.us/, but it seems it is not really working because there are no active projects, or maybe I'm missing something.

At this moment, how could I fund a Drupal project?

# Answer
> 2 votes
What you're asking for is not an obvious task to get completed.

The most recent, fairly successful, funding campaign that I'm aware of is for upgrading the Rules module to D8, via `#d8rules`. For some pointers about it, start from the community promotion ad (disclosure: I posted it) which looks like so:

Depending on what the subject of your project is, maybe your project also fits the criteria for starting a similar ad ... free of charge (just a relevant image and URL will get you going)!

# Answer
> 2 votes
If your project uses company's X API or library, you can try approaching company X about funding your project. As it would be beneficial for them if people don't have to invent the wheel in order to use their service.

---
Tags: community-official-site
---


# Question
Title: How can I be sure configuration is never changed on live system?
The documentation for the Drupal 8 configuration manager says:

> Making configuration changes on a live site is not recommended.

When managing a site used by dozens of content managers, how can I make sure that this really never happens? Is there a way to prevent this with permission settings? For me it's still not really clear which permissions to set, to make sure those users are never able to change the configuration.

# Answer
One option is to use https://www.drupal.org/project/config\_readonly, it enforces that config writes can not happen on production.

So far, I haven't built/maintained a D8 site where that approach was practical. Most of our sites rely quite heavily on contact forms for example, with workflows where content managers create contact forms as well. And sometimes quick changes are necessary, e.g. for services and integrations.

One option to deal with that is to use a project like https://www.drupal.org/project/config\_split, which allows to keep a part of configuration outside of git and not have it overwritten by deployments. So far, we just do a config export on production, commit that to the production branch and then merge the feature branches that we want to deploy. There's some risk for conflicts, but that doesn't happen often.

But sure, there are sites where it is critical that every change is reviewed and approved first, before it can be deployed, then something like config\_readonly is useful. I wouldn't enforce it just because some d.o page says so, you need to figure out what works best for your site and workflows.
> 1 votes

# Answer
I can speak for developing with Drupal 7 but I'm sure the concept can be translated.

**Content Contributor Role** To answer your question about controlling permissions, just take a look at this documentation on Drupal 8 permissions. Create a specific role for content contributors and give them only the specific permissions you want them to have, e.g. nothing with configurations. You can bulk reassign all your content contributors to the new role you created, if you don't already have it.

Prevent users from logging into the admin account by protecting the password and making sure there is only one admin account on production. All content contributors should only have access to functions which build data, such as adding or editing nodes and editing the menu.

**Development Workflow** Rarely log into production as an admin and use git and features to push everything up into it after testing the code and data in a staging environment. I work on a local environment and push the code up to staging while I import the database from prod to staging. If everything checks out in staging, I push the code into production. No configurations need to happen in production because they can all be featurized in development. Thus, preventing access to making configuration changes on production works just fine.

All developers develop locally and the staging environment is where the design team approves things before they are deployed. This article on Drupal development with Git is my bible.
> 0 votes

---
Tags: 8, configuration
---


# Question
Title: Error throwing for user field populated through Views: Filter by an entity reference view
I am working on a ticket system in my current project (Drupal 8) where user can assign a ticket to particular user. The user field is populated through entity reference and it is filtered using 'Views: Filter by an entity reference' (users belonged to a particular role need to be shown there). For normal users its resulting in 500 Internal server error. It works perfectly if I give 'Administer users' permission to current user role. But without that it will break. I have given 'view user information' permission to all users. Is there any work around without giving 'Administer users' permission to all users as it is not a viable option.

# Answer
> 0 votes
If you need to show the users from a particular role you don't need to rely on views filter option. Default method is enough, there will be an option to filter the users using roles. I know its the answer that you are seeking. But its a work around. But if you need to add other filter parameters this method will not be enough.

---
Tags: views, entities
---


title: Bulk assign paths to nodes

text:
# Question
Title: Bulk assign paths to nodes
I have a bespoke content type with a lot of nodes, but alias urls have not been assigned to them. I need to bulk assign them consistent alias. I know on Drupal 7 this is possible to do using pathauto, however I have installed that for Drupal 8 and the batch assignment doesn't seem to be working yet. Is there another efficient way this can be done?

# Answer
1) Make sure you have set up a working alias for your content type at /admin/config/search/path/patterns

2) Go to /admin/config/search/path/update\_bulk

3) check "Content"

4) Submit

I have just tested this on my local dev environment by going in the db and deleting the alias to one node:

```
delete from url_alias where source = '/node/2940'

```

and running the bulk operation generated an alias for all unaliased nodes (which just happened to be the only one I deleted).

So if the bulk operation isn't working for you, it may be that you don't have a pattern set up for your content type (node bundle).

Check at /admin/config/search/path/patterns and make sure you have a working pattern set up for your content type.
> 2 votes

# Answer
Also you need to make sure the flag **Generate automatic URL alias** is set before you perform the bulk update (/admin/config/search/path/update\_bulk)

```
$entity->get('path')->__set('pathauto', TRUE);

```
> 0 votes

---
Tags: 8, path-aliases
---


title: How to expose $user->data to views?

text:
# Question
Title: How to expose $user->data to views?
Do I need to use hook\_views\_data like a custom table?

# Answer
> 4 votes
Actually, this can be done within the Views UI by selecting the user:data field and then choosing a key.

# Answer
> -1 votes
You need to first add relationship with 'author' in the view and accordingly you will get the user data fields which you can use in your fields as well as in filters.

---
Tags: views, users, entities
---


# Question
Title: Filtering exposed filters with views_get_view_result() function
I have built a module so that I can display PDFs with phpwkhtmltopdf. I am currently calling my view data using:

```
$view = views_get_view_result('course_catalog');

```

My question is, is there a way to have filter my exposed filters with this function? If not, what is the best way to go about this? --I suppose I could manually filter through the results with PHP, but that hardly seems efficient.

# Answer
It seems `views_get_view_result` does not allow setting filters: https://www.drupal.org/node/1428696

Instead of using `views_get_view_result`, you might try with other functions of the Views API:

```
$view = views_get_view('course_catalog');
$view->set_exposed_input($my_exposed_input);
$view->init_display();
$view->pre_execute();
$view->execute();
$result = $view->result;

```

You can check the documentation for the set\_exposed\_input method, and also this related Drupal Answers question, for alternatives: How to change programmatically exposed filters in views
> 4 votes

---
Tags: views
---


# Question
Title: How to put the website in the read only mode?
how to freeze the website so that any changes cannot be made by the user on the websites? I want to put the website on the read only mode . Read only mode module is there but is this possible through coding?

# Answer
```
/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter($form, $form_state, $form_id) {
  $form['#attributes'] = array('disabled' => TRUE);
  drupal_set_message("Website is currently in read only mode. During this it is not possible to change site content", "warning");
}

```

You can use above code in your custom module.
> 2 votes

---
Tags: 7
---


# Question
Title: Proper way to access data in a custom table
I have a module for which I've created a custom table in the database. I want to access various data in the table.

Since normally accessing content types is done via the abstraction layer provided by Drupal itself I'm wondering what would be the most "drupal" way to access the data in my table.

I assume I could simply use `Database::connection` class and function, but it seems a tad brutal(so to speak).

Would it make sense to create a repository or am I just overthinking this and should just go ahead and use the `Database` class and be done with it.

# Answer
If this question was about D7, you could start from what's suggested in the Developers Guide that comes with the Forena module (disclosure: I'm a co-maintainer of the D7 version). Here is a quote from its introduction:

Forena implements custom hooks to allow the report engine to be extended in many ways. Forena does use OOP methodologies, but also leverages the observer pattern so prevalent in Drupal.

> There is then a common pattern that is used to extend Forena:
>
> * Implement a custom php class that lives in your module directory. You may extend any of the Forena classes, or write your own from scratch.
> * Implement the expected registration methods in your class (e.g. templates, formats).
> * In your module implement a hook (e.g. mymodule\_forena\_controls) that tells Forena the location of your class definition file.

These days, Forena has a dev version for D8 also, for which it's current status can be summarized like so (from it's release notes):

> Basic rendering of reports and document types are complete, however the GUI version of the report writer has not yet been ported. Sufficed to say, this version can be used by Drupal 8 report writers who are comfortable writing .frx files and sql elements by hand.

Some more details to help you digest these release notes:

* "*SQL elements*" refers to Data Blocks and the Data Sources they relate to, as explained in the Data Guide.
* The "*.FRX files*" are the actual specifications of how you want you report to look like, as explained in the FRX Reporting Reference.
* The "*GUI version of the report writer*" is what is explained in the WYSIWYG Reporting Guide.
> 1 votes

---
Tags: 8
---


# Question
Title: Why form redirects to encoded url when having GET params?
I have a simple form with 1 select and I want it after the form submit to redirect to the same URL, but with added GET params.

---

So in a form submit I added:

```
$form_state['redirect'] = url(arg(0).'/'.arg(1).'/'.arg(2), array(
  'query' => array(
      'brand' => $state['values']['brand'],
      'categ' => arg(2)
)));

```

Which redirects to wrong encoded url:

> /produkty/vlasy%3Fbrand%3D118%26categ%3D27

---

But It works well when I use drupal goto (this is not recommended):

```
  drupal_goto(arg(0).'/'.arg(1).'/'.arg(2), array(
      'query' => array(
          'brand' => $state['values']['brand'],
          'categ' => arg(2)
  )));

```

> /produkty/vlasy?brand=118&categ=27

---

Why is it so?

# Answer
You just need to adjust the param value from a string to an array for `$form_state['redirect']`

It is in the documentation for `drupal_redirect_form`

> $form\_state\['redirect'\] determines where to redirect the user. This can be set either to a string (the path to redirect to), or an array of arguments for drupal\_goto().

Example:

```
$form_state['redirect'] = array(
  arg(0) . '/' . arg(1) . '/' . arg(2),
  'query' => array(
        'brand' => $form_state['values']['brand'],
        'categ' => arg(2)
  )
);

```
> 1 votes

# Answer
Use urldecode() function.

```
$redirect_url = url(arg(0).'/'.arg(1).'/'.arg(2), array(
  'query' => array(
      'brand' => $state['values']['brand'],
      'categ' => arg(2)
)));
$form_state['redirect'] = urldecode($redirect_url);

```

Output: /produkty/vlasy?brand=118&categ=27
> -3 votes

---
Tags: forms, uri, redirection
---


title: Edit account menu item in user menu

text:
# Question
Title: Edit account menu item in user menu
I want to add edit account menu item in user menu, I want the URL to be user/{user\_id}/edit. How can I achieve this without menu\_token module. I also tried creating menu item programatically as follow

```
$items = array();
  global $user;
  $user_id = $user->uid;
  $items['user/' . $user_id . '/edit'] = array(
    'title' => 'Edit account',
    'access callback' => 'user_is_anonymous',
    'menu_name' => 'user-menu',
    'type' => MENU_SUGGESTED_ITEM,
  );

  return $items;

```

But newly created menu item only shows at back-end i.e. at structure/menu/user-menu but it doesn't display it on front-end.

# Answer
> 1 votes
```
function hook_menu() {
  $items = array();
  global $user;
  $user_id = $user->uid;
  $items['user/' . $user_id . '/edit'] = array(
    'title' => 'Edit account',
    'page callback' => 'MYMODULE_user_edit',
    'access callback' => 'MYMODULE_user_edit_access',
    'menu_name' => 'user-menu',
    'type' => MENU_SUGGESTED_ITEM,
    'file' => 'user.pages.inc',
    'file path' => 'modules/user'
  );

  return $items;
}

function MYMODULE_user_edit() {
  global $user;
  $account = user_load($user->uid);
  return drupal_get_form('user_profile_form', $account);
}

function MYMODULE_user_edit_access(){
  global $user;
  return user_edit_access($user);
}

```

Try above code. :)

---
Tags: hooks, navigation
---


# Question
Title: How to output correctly an html_restricted textarea field in Twig?
I don't know if that stupid question has already been asked...

But how should I output a field type "text\_long" in Twig ?

Now what I do is to set myself an array with that :

```
$data = $journalist->field_bio->getValue();

$user['bio'] = [
                    '#type' => 'processed_text',
                    '#text' => $data[0]['value'],
                    '#format' => 'full_html'
               ];

```

Because I cannot find the filter to render a text\_long in html.

In the twig I tried : {{ user.bio | raw }}, {{ user.bio | render }}...

=\> What's the drupal 8 way to handle that ?

# Answer
> 2 votes
The Drupal 8 way would be to use a view mode and let the field formatter do its work.

If you want to do this in custom code you can build the render element for processed text like you did in the question, but use the text format stored in the field:

```
$user['bio'] = [
  '#type' => 'processed_text',
  '#text' => $data[0]['value'],
  '#format' => $data[0]['format'],
];

```

Then you are sure, that the text filters are applied configured in the format, that the user who filled in the text field had permission to use.

To output the variable in twig you don't need any filters, they are applied automatically by the render element:

```
{{ user.bio }}

```

---

Edit for the question in the comment, how to render a field without a view mode. There is a way to do this. You can view a field by providing the display options in an array:

```
$user['bio'] = $journalist->field_bio->view(['label' => 'hidden', 'type' => 'text_default']);

```

But this is as expensive as rendering the complete entity and is not optimized for caching. So use it only if you can't figure out a way how to render whole entities in view modes.

---
Tags: theming, 8
---


# Question
Title: How can I login to my local drupal site 8.3.1 which was under maintence mode
I just logout to see what will the home page look like. Now, I can't login into my local site.

# Answer
> 1 votes
You can also try to login by enter below url.

```
http://example.com/?q=admin
or
http://example.com/user

```

# Answer
> 0 votes
Just go to /user/login, it works even in maintenance mode, and then sign in as an admin.

---
Tags: users, maintenance-mode
---


# Question
Title: How to restrict access to edit image file while still giving permission to edit image title?
I want to restrict the possibility to edit or delete the image file, but still make it possible for users to edit the alt and title attribute.

What is best approach to do that?

# Answer
> 0 votes
It can be done using Image Field Permissions module.

The Image Field Permissions allows you to set permissions to view, create and edit the image file, title and alt attributes.

---
Tags: 8, users, media
---


title: Dynamic content with a view and a block

text:
# Question
Title: Dynamic content with a view and a block
I'm new to Drupal (using Drupal 8) and have been struggling to get content from a block I've create to display when accessing the view.

I've created a "service" view (page) which lives at the path "/service". I've configured the view to display the desired fields from the "service" content type. The view uses a contextual filter on the title of the "service" content type which allows clean URLs to work "/service/name-of-service"

The above works well. I'm running into problems with an "info" view (block) that I've created. The "info" block pulls in different fields from the same "service" content type. I decided to use a block for the remaining fields as it allowed me to place them in a specific block region that works for our desired page layout.

I've tried setting up a contextual filter in the block to filter by "ID" and provided a default value of "Content ID from URL", but I can't get this to work, no fields display at all. If I flip the setting to "Display all results for the specified field", fields do display, however, the content of the fields displaying in the "info" block is not pulling from the same node (because there is no contextual filter).

Is there a way I can setup a contextual filter to accomplish this? I've been able to use the contextual filter by ID successfully when working with the node itself, but can't get the same behavior when using views.

# Answer
> 0 votes
I was able to get this to work with the following contextual filter in my "info" block.

Filter by "Title"

---
Tags: views, blocks
---


title: What's wrong in this insert sql?

text:
# Question
Title: What's wrong in this insert sql?
I am trying to create an entity programmatically.

My code:

```
//my entity
use \Drupal\my_module\Entity\my_entity;

$entity = my_entity::create(
      [
          'label' => "token",
          'type' => "bundle",
          'uuid' => $uuid,
          'user_id' => $user->id(),
          'entity_type' => $node->getType(),
          'entity_id' => $node->id(),
          'value' => 10,
          'read' => false,
          'created' => time(),
          'changed' => time()
      ]
  )->save();

```

**However, on save, it gives me this sql error. What am I missing?**

> Drupal\Core\Entity\EntityStorageException: SQLSTATE\[42000\]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'read, created, changed) VALUES ('bundle', '4a6ca0e3-89f0-46da-8889-c42a7f45ec4a'' at line 1: INSERT INTO {my\_table} (type, uuid, user\_id, entity\_type, entity\_id, value, read, created, changed) VALUES (:db\_insert\_placeholder\_0, :db\_insert\_placeholder\_1, :db\_insert\_placeholder\_2, :db\_insert\_placeholder\_3, :db\_insert\_placeholder\_4, :db\_insert\_placeholder\_5, :db\_insert\_placeholder\_6, :db\_insert\_placeholder\_7, :db\_insert\_placeholder\_8); Array ( \[:db\_insert\_placeholder\_0\] =\> bundle \[:db\_insert\_placeholder\_1\] =\> 4a6ca0e3-89f0-46da-8889-c42a7f45ec4a \[:db\_insert\_placeholder\_2\] =\> 2 \[:db\_insert\_placeholder\_3\] =\> article \[:db\_insert\_placeholder\_4\] =\> 14 \[:db\_insert\_placeholder\_5\] =\> 10 \[:db\_insert\_placeholder\_6\] =\> 0 \[:db\_insert\_placeholder\_7\] =\> 1493818295 \[:db\_insert\_placeholder\_8\] =\> 1493818295 ) in Drupal\Core\Entity\Sql\SqlContentEntityStorage-\>save() (line 770 of core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php).

# Answer
https://www.drupal.org/docs/develop/coding-standards/list-of-sql-reserved-words Maybe "read" should have quotes (\`\`) around it in order for this to work. I am uncertain why this is not done automatically.
> 3 votes

# Answer
This is not the exact one but You can check this example.

```
use \Drupal\node\Entity\Node;
use \Drupal\file\Entity\File;

// Create file object from remote URL.
$data = file_get_contents('https://www.drupal.org/files/druplicon.small_.png');
$file = file_save_data($data, 'public://druplicon.png', FILE_EXISTS_REPLACE);

// Create node object with attached file.
$node = Node::create([
  'type'        => 'article',
  'title'       => 'Druplicon test',
  'field_image' => [
    'target_id' => $file->id(),
    'alt' => 'Hello world',
    'title' => 'Goodbye world'
  ],
]);
$node->save();

```

More Here
> 2 votes

# Answer
!Ahhh. What a silly idea to get caught in the middle.

When I checked manually in `phpmyadmin` it says `read` is system reserved. Posting this answer as separate so that it will be clear enough for others. @Ruben deserves the point for that link:
> 0 votes

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


title: Youtube feed block

text:
# Question
Title: Youtube feed block
I'm trying to get my youtube channel feed on my drupal 7 website. I searched a lot on the internet, but most are old answers that doesn't work anymore. Modules like Youtube Channel Block, ... Even the iframe solutions doesn't work anymore.

My question is simple: How can I get my youtube channel feed on a page / block without scripting a whole module with the Youtube API? It doesn't have to play on the page/block. I don't want to add the video's one by one..

# Answer
Use the following URL to access feeds:

```
https://www.youtube.com/feeds/videos.xml?playlist_id=YOUR_YOUTUBE_PLAYLIST_NUMBER
```
> 0 votes

---
Tags: 7, blocks
---


title: Remove trailing whitespace from a field

text:
# Question
Title: Remove trailing whitespace from a field
Here is a slice of code from my twig template, which outputs the contents of some fields into a p tag:

```
<p>
    {{ content.field_story_program_name }},
    {{ content.field_story_relationship}},
    {{ content.field_story_city }},
    {{ content.field_story_state }}
</p>

```

The output on the page renders a trailing white space after each field's content, which I don't want (because it creates spaces before the commas):

> Local Head Start Program Provider , Head Start administrator , Los Angeles , CA

Things I've tried:

* Based on this post, I checked my field.html.twig template to see if it's introducing spaces (it's not).
* Tried putting a - in the `{% endfor %}` on that field.html.twig template anyway to see if it would help: `{% endfor -%}` (it didn't).
* Put all of my values on one line in case a carriage return was being interpreted as whitespace (I think that was a Drupal 7 issue that I read) as in:
`{{ content.field_story_first_name }} {{ content.field_story_last_name }}, {{ content.field_story_program_name }}, ...etc`
But that didn't fix it
* Tried `{% spaceless %}` though I know it's just for spaces *between* tags and so of course that didn't end up helping
* Using the `|trim` Twig filter, which makes the entire value disappear and produces a rendering error. I suppose that *technically* solves the whitespace problem... ;)

Can anyone help give me a clue? I would like to either

1. Find out where the extra space is coming from and turn it off there, or
2. Use the appropriate Twig filter to remove the space

# Answer
> 7 votes
Okay, here is what finally worked: wrap every individual field in `{% spaceless %}` (not just the whole block) and use render and trim together. Trim alone makes the variable disappear. Here's my markup:

```
<p>
  {% spaceless %}{{ content.field_story_program_name|render|trim }}{% endspaceless %},
  {% spaceless %}{{ content.field_story_relationship|render|trim }}{% endspaceless %},
  {% spaceless %}{{ content.field_story_city|render|trim }}{% endspaceless %},
  {{ content.field_story_state }}
</p>

```

Extra thanks to @Cyclonecode for giving me a variety of tricks to try.

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


# Question
Title: How to allow a route to a user as long as he has the good role?
Maybe this is a noob question but here goes:

I have a menu a menu that contains four links. However, I need one of the items to be accessible only if the current user has "beneficiary" as role.

Since the user's 'roles' is an array containing all kind of roles, how can I set my route in a way that as long as the user has the correct role ?

IE, let's say that a random user has the following:

```
$user['roles'] = ['authenticated', 'beneficiary', 'elected'];

```

and would pass, but another random user having the following:

```
$user['roles'] = ['authenticated', 'elected'];

```

wouldn't.

I'm pretty sure there is a way but I can't find explicitely what I'm looking for in Drupal's documentation

Thank you in advance

# Answer
I've never personally tried this, but it looks like in your routing.yml file, you can specify a \_role permission under requirements:

https://www.drupal.org/docs/8/api/routing-system/structure-of-routes

```
my_module.your_route:
  path: '/your_menu_path'
  defaults:
    _controller: '\path\to\your\controller'
    _title: 'Menu title'
  requirements:
    _role: 'beneficiary'

```
> 18 votes

---
Tags: 8, routes, users
---


# Question
Title: Paste field content directly to node.html.twig?
The content type article has a field called field\_kategorie. It should be output in the URL in the title of the node with.

node.html.twig doesn't work as expected.

```
<a href="{{ url }}" rel="bookmark">{{ field_kategorie }}{{ label }}</a>

```

How to do that?

# Answer
`{{ node.field_test.value }}` works in node.html.twig for "normal" fields, not for taxonomy fields.
> 0 votes

---
Tags: theming, 8, nodes
---