title: Create a user using a single PHP file

text:
# Question
Title: Create a user using a single PHP file
I have tried every possible ways to create a user account using only a single PHP file without writing a module. I want to create a portal in which visitors can subscribe or register themselves and do something after they logged in. I have also a mobile application (Android and iOS) in which my app users can register (subscribe) and use the app in their mobile phone. Both the web application and the mobile application use the same API to create a Drupal 8 user. Is there anyone who help me out to achieve this?

# Answer
> 0 votes
If you want a single php file you can use a drush shell script:

```
#!/usr/bin/env drush

use Drupal\user\Entity\User;

    $user = User::create(['name' => 'testuser', 'status' => TRUE]);
    $user->save();

```

For more information see https://github.com/drush-ops/drush/blob/master/docs/shellscripts.md

A better approach might be to use REST, see https://www.drupal.org/node/2754633

# Answer
> 0 votes
Eyosiyas Tadele, Like 4k4 said, You don't even need to write any PHP code, not even single file and definitely not a module if you are using Drupal 8 core REST module.

Here is a sample Drupal 8 Android app https://github.com/onedrupal/One-Drupal-Android that uses core REST API to POST node. Similarly you can POST to user registration API.

You can use https://www.drupal.org/project/restui contrib module to enable and configure these APIs once you have enabled, you can export as a config yml file if you want to move the REST API config from dev environment to prod environment like the yml file at https://cgit.drupalcode.org/one\_api/tree/config/install/rest.resource.entity.user.yml

---
Tags: users
---


# Question
Title: Re-authenticate a user with X-CSRF-Token
I am writing an Android application that consumes the Drupal 8 REST features. I have managed to write REST resources and make API calls with the android app to these resources with success.

My question is about the login and sessions. When the users logs in for the first time we get X-CSRF-Token, which has an expiration date. I also use this token to authenticate myself when making calls to the REST resources.

Does Drupal has a REST feature that refreshes the token without having to enter the user credentials again?

The idea is to have an app on which you log in only once until the users logs out manually.

# Answer
Rasjaad, You can use android account manager https://developer.android.com/reference/android/accounts/AccountManager for this purpose

Here is a sample Drupal 8 Android app code that uses account manager to reauthenticate. https://github.com/onedrupal/One-Drupal-Android

https://github.com/onedrupal/One-Drupal-Android/blob/master/app/src/main/java/com/technikh/onedrupal/activities/ActivityAuthentication.java At the launch of the activity AccountManager.getAuthTokenByFeatures is called

```
mAccountManager.getAuthTokenByFeatures(AccountUtils.ACCOUNT_TYPE, AccountUtils.AUTH_TOKEN_TYPE, null, this, null, null, new ActivityAuthentication.GetAuthTokenCallback(), null);

```

Here is the AccountAuthenticator https://github.com/onedrupal/One-Drupal-Android/blob/master/app/src/main/java/com/technikh/onedrupal/authenticator/AccountAuthenticator.java

```
authToken = AccountUtils.mServerAuthenticator.signIn(site_protocol+site_domain, account.name, password);

```
> 0 votes

---
Tags: 8
---


# Question
Title: Why does trying to POST a node from Android result in "HTTP/1.1 415 Unsupported Media Type"?
I used the following code to post some data to my site. I tested the site with Postman using the same data and it works properly, but when running the following code on Android Studio, `response.getStatusLine()` returns *HTTP/1.1 415 Unsupported Media Type*.

```
       HttpClient httpClient = new DefaultHttpClient();
       HttpPost httpPost = new HttpPost("http://www.example.com/entity/node");
       HttpResponse response = null;
       String responseBody = "";

       try{
           JSONObject json = new JSONObject();
           JSONObject c0 = new JSONObject();
           JSONObject c00 = new JSONObject();
           JSONObject c1 = new JSONObject();
           JSONObject c2 = new JSONObject();

           json.put("_links",c0);
           json.put("title",c1);
           json.put("type",c2);

           c0.put("type",c00);
           c00.put("href","http://www.example.com/rest/type/node/article");
           c1.put("value", "test string");
           c2.put("target_id", "article");

           String base64EncodedCredentials = "Basic " + Base64.encodeToString(
                   ("user"+ ":" + "pass").getBytes(),
                   Base64.NO_WRAP);

           StringEntity se = new StringEntity(json.toString());

           se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));

           httpPost.setHeader(HTTP.CONTENT_TYPE, "application/json");
           httpPost.setHeader("Authorization", base64EncodedCredentials);

           httpPost.setEntity(se);

           // Execute HTTP Post Request
           response = httpClient.execute(httpPost);

           String jsonResponse = EntityUtils.toString(response.getEntity());
           JSONObject jsonObj = new JSONObject(jsonResponse);

           if (response.getStatusLine().getStatusCode() == 200) {
               Log.v("response ok", "ok response :/");
           } else {
               Log.v("response not ok", "Something went wrong :/");
           }
       catch (Exception e){
           Log.v("Error posting:",e.getMessage());
       }

```

I tested each of these lines separately and together, but none of them work.

```
    se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));

           httpPost.setHeader(HTTP.CONTENT_TYPE, "application/json");

```

Why does it return *HTTP/1.1 415 Unsupported Media Type*?

# Answer
I have faced same problem with same situation as you described above. After spending 2-3 hours I have got data through:

```
$formdata = file_get_contents('php://input');

```

It's worked for me.
> 0 votes

# Answer
Mde, Instead of using HttpClient try using OkHttpClient like this Drupal 8 Android app at https://github.com/onedrupal/One-Drupal-Android.

```
request = new Request.Builder()
                        .header("Content-Type", "application/json")
                        .url(url)
                        .patch(api_body)
                        .build();
OkHttpClient client = new OkHttpClient.Builder()
                .connectTimeout(20, TimeUnit.SECONDS)
                .writeTimeout(20, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
                .addInterceptor(new AddCookiesInterceptor())
                .build();

```

AddCookiesInterceptor at https://github.com/onedrupal/One-Drupal-Android/blob/master/app/src/main/java/com/technikh/onedrupal/network/AddCookiesInterceptor.java

```
public class AddCookiesInterceptor implements Interceptor {
    @Override
    public Response intercept(Interceptor.Chain chain) throws IOException {
        Request.Builder builder = chain.request().newBuilder();
.......
Preferences.getDefaultPreferences().getStringSet(Preferences.PREF_COOKIES, new HashSet<>());
        for (String cookie : preferences) {
            builder.addHeader("Cookie", cookie);
        }
......
        builder.addHeader("X-CSRF-Token", mAuthPreferences.getAuthToken());

        return chain.proceed(builder.build());
    }
}

```
> 0 votes

---
Tags: 8
---


# Question
Title: How do I send user credentials and get the access token?
I am linking a Drupal site to an Android application. With the help of the Simple OAuth module, users will log in to my android app using their Drupal site credentials.

I understand that once the client application has the access token, it can be included in the headers of any GET request to fetch JSON content from Drupal. I also know that https://example.com//simple-oauth/refresh will give a new access token, having the refresh token.

What should I do if both access and the refresh tokens are already expired? How do I get them from scratch? What is the URL to ask for the token, and how do I include the credentials with that via HTTP headers or in the URL?

Is there something I'm not aware of about this way of authenticating?

# Answer
Moqbel, Here is a Drupal 8 Android app code that uses Android accountManager to send user credentials and get the access token. https://github.com/onedrupal/One-Drupal-Android

Whan a token is expired, AccountManager can be used to get a fresh token. https://github.com/onedrupal/One-Drupal-Android/blob/master/app/src/main/java/com/technikh/onedrupal/activities/ActivityAuthentication.java At the launch of the activity AccountManager.getAuthTokenByFeatures is called

```
mAccountManager.getAuthTokenByFeatures(AccountUtils.ACCOUNT_TYPE, AccountUtils.AUTH_TOKEN_TYPE, null, this, null, null, new ActivityAuthentication.GetAuthTokenCallback(), null);

```

Here is the AccountAuthenticator https://github.com/onedrupal/One-Drupal-Android/blob/master/app/src/main/java/com/technikh/onedrupal/authenticator/AccountAuthenticator.java

```
authToken = AccountUtils.mServerAuthenticator.signIn(site_protocol+site_domain, account.name, password);

```

It uses cookie auth by using endpoint /user/login?\_format=json at https://github.com/onedrupal/One-Drupal-Android/blob/master/app/src/main/java/com/technikh/onedrupal/provider/MyServerAuthenticator.java

But Android AccountManager also works with OAuth.

from https://developer.android.com/training/id-auth/authenticate

> The only way to discover whether a token is expired or not is to contact the server, and it would be wasteful and expensive for AccountManager to continually go online to check the state of all of its tokens.
>
> Because expired tokens are such a common occurrence, and fixing them is so easy, many applications just assume the token has expired before even asking for it. If renewing a token is a cheap operation for your server, you might prefer to call AccountManager.invalidateAuthToken() before the first call to AccountManager.getAuthToken(), and spare yourself the need to request an auth token twice.
> 0 votes

---
Tags: 8
---


# Question
Title: How can I expose Drupal data to external applications?
How can I expose data from my Drupal site via web services to external applications such as iPhone or Android?

# Answer
One of the most popular solutions is the Services module. It takes a little bit of set-up and know-how but it's very flexible in what it can output and what formats you need it. It's the solution we used at Palantir.net to provide data to our DrupalCon Chicago Android and iOS apps.
> 14 votes

# Answer
One option is to use RSS which is enabled by default. You can use RSS at http://example.com/rss.xml by default, or if you're using something like the views module, you can always set up an RSS feed for a specific view, to limit the data in the RSS feed to a specific type, or other filters.
> 1 votes

# Answer
Modules can also implement hook\_xmlrpc(), and hook\_xmlrpc\_alter().
Depending on the data you need to exchange with the external applications, and from the format they need, you could also follow this approach.
> 0 votes

# Answer
For Drupal 8, it's best to use core REST API module. Here is a Drupal 8 Android app https://github.com/onedrupal/One-Drupal-Android that uses core REST APIs.
> 0 votes

---
Tags: services
---


# Question
Title: theme style.css is not loading for custom theme
I am trying to learn Drupal 8 theme development. I am trying to create basic theme **My Folder structure**

```
|-themes
  |  |-custom
  |  |  |-contra
  |  |  |  |-css
  |  |  |  |  |-style.css
  |  |  |  |-contra.info.yml
  |  |  |  |-contra.libraries.yml

```

My contra.info.yml is as follows:

```
name: contra
description: 'Drupal 8 starter theme'
type: theme
core: 8.x
libraries:
   -'contra/global-styling'

```

My contra.libraries.yml is as follows:

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

```

I have cleared the cache in Admin-\>Configuration-\>Development and also refreshed my browser but I dont see the style.css loaded in view source.

# Answer
Try adjusting your spacing. 2 spaces are required.

.info.yml:

```
name: contra
description: 'Drupal 8 starter theme'
type: theme
core: 8.x
libraries:
  - contra/global-styling

```

.libraries.yml:

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

```

Also, take a look at https://www.drupal.org/docs/8/theming/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-theme
> 0 votes

---
Tags: theming
---


# Question
Title: Is it possible to export my website to a native iOS/Android application?
I'm new to the EZPublish CMS and I see that he give you the facility to export your website into an Android or iPhone application.

Is there any way to do the same with Drupal?

# Answer
> 5 votes
Mobile App Generator exports a website to plain .html pages so that PhoneGap can compile it into native mobile apps.

> Mobile App Generator assists in creating native multi-platform PhoneGap mobile applications for Apple iOS(iPhone, iPad), Google Android, Palm, Symbian, BlackBerry and more.

If you want to manage the website through mobile App then take a look at this module Drupad

> Drupad.module is the companion module for the iPhone™ / iPod touch™ application

# Answer
> 0 votes
If you want to manage your Drupal 8 website through mobile App then take a look at this android app https://github.com/onedrupal/One-Drupal-Android

In play store at https://play.google.com/store/apps/details?id=com.technikh.onedrupal&pcampaignid=MKT-Other-global-all-co-prtnr-py-PartBadge-Mar2515-1

Companion drupal module https://www.drupal.org/project/one\_api

Login, Create & edit nodes, Upload images, Publish, Unpublish, Promote to front page, remove from front page(Demote)....

---
Tags: importing-exporting
---


# Question
Title: What is the correct way of logging in through services from android?
I currently have an app in development where I use services 3 on drupal 7 to login to my site. I do this by simply passing in the username and password parameters to a json object and use httppost to post them to service endpoint. Using the response I grab the cookie and store it in sharedpreferences on android which is used in all the following requests. I have this cookie set to be used for several days so the user wont require login again. Do I have any reason to be concerned about the security of this (I dont store any passwords) and if so what are the extra steps I can take and how to beef up the security but still allow for users to remain logged in? I have played around with the oauth module a bit but it seems rather complicated to implement on both drupal side and android. If oauth is my best option what are the steps to take to implement it with drupal and android?

# Answer
You can use Android AccountManager over https to be more secure. Like this Drupal 8 Android app at https://github.com/onedrupal/One-Drupal-Android.
> 0 votes

# Answer
You should definitely be doing some sort of encrypted key exchange, otherwise someone could post the login info to their own server and respond with a positive result!

I've never used the module you're referring to, but Drupal bootstrap is VERY easy to set up.
> -1 votes

# Answer
I think logging in then using the session id as a key for authentication is ok there. However, to make it more secure, you should do all the API requests containing the session token over HTTPS.
> -1 votes

---
Tags: services, authentication-authorization
---


# Question
Title: Is there any way to use Java for developing?
I am a programmer, I primarily program in Java, but I am now working with Drupal. Drupal uses HTML and CSS for most of its design, from blocks to views, but I have discovered it's much harder to create things that are dynamically designed.

What I am used to is designing things in Android programming where XML is used to design the layout and Java to control it.

Is there any way to do this in Drupal that allows me to create things like blocks using Java or even JavaScript? Is there a way to develop my own modules using Java, or can I only do it in PHP?

# Answer
> 4 votes
**Drupal is a PHP web framework.** The tools that is uses are those of the web. If you are trying to implement something with XML and Java you are not really using Drupal. There are skills that you have to learn in order to create web pages which are different from those on a phone.

Having said that. I believe that there are some Android front ends for Drupal. That may be a good starting point for you.

# Answer
> 0 votes
Look at web services. Write your web service in Java and then write a Drupal module to consume/interact with it.

# Answer
> 0 votes
For certain applications, such as computations and interactive visualization of secure data, java is one of the only viable solutions. I use it to visualize secured datasets over public Internet connections via a Drupal Services based API. The java applet is passed the API end-point at launch, and communications with the applet take place RESTfully over https.

Any dataset visualized in most web technologies can have their data scrapped off the page; but not in a java applet. It is easy to imagine situations where this is useful: banking, market research, product designs, legal contracts and agreements, any secured data, really.

# Answer
> 0 votes
You can use headless Drupal as backend and like Jeremy French said, use Android as front end. Here is a Drupal 8 Android app https://github.com/onedrupal/One-Drupal-Android

https://play.google.com/store/apps/details?id=com.technikh.onedrupal

---
Tags: 7
---


title: twig encoding html

text:
# Question
Title: twig encoding html
I have a view that has two blocks. The blocks are essentially the same except for their filtering options. One uses contextual filters and the other uses BEF exposed filters.

Both output matching node body content in full.

Both make use of the same twig template: views-view-fields--VIEW\_NAME.html.twig

```
<h3 class="accordion-header">{{ fields.title.content }}</h3>
<div class="accordion-content">{{ fields.body.content }}</div>

```

If I add:

```
{{  dump(fields.body.content) }}

```

Working version shows:

```
object(Drupal\Core\Render\Markup)[8515]
  protected 'string' => string '

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'views_view_field' -->
<!-- BEGIN OUTPUT from 'core/modules/views/templates/views-view-field.html.twig' -->
<p>Membership universal content</p>

<!-- END OUTPUT from 'core/modules/views/templates/views-view-field.html.twig' -->

```

Non-working version shows:

```
object(Drupal\Core\Render\Markup)[2061]
  protected 'string' => string '

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'views_view_field' -->
<!-- BEGIN OUTPUT from 'core/modules/views/templates/views-view-field.html.twig' -->
<p><p>Membership universal content</p></p>

<!-- END OUTPUT from 'core/modules/views/templates/views-view-field.html.twig' -->

```

I have a work around by adding autoescape and convert\_encoding

```
{% autoescape false %}

<h3 class="accordion-header">{{ fields.title.content }}</h3>
<div class="accordion-content">{{ fields.body.content|convert_encoding('UTF-8', 'HTML-ENTITIES') }}</div>

{% endautoescape %}

```

But this is now adding additional empty p tags before and after.

I don't understand why the output for one is escaped and the output for the other is not. Any pointers would be great, thank you.

# Answer
the offending view also had aggregation enabled. To stop the escaped html, open the field's aggregation settings and include 'format'.
> 3 votes

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


title: Using innerJoin() in TableSort

text:
# Question
Title: Using innerJoin() in TableSort
In the examples modules I see a simple example of tableSort with one table. Searching online I find a post where they claim Drupal 7 allowed a db\_select() object to be created and then extended it with a join(), and then the final -\>extend('TableSort');

https://www.drupal.org/forum/support/module-development-and-code-questions/2011-12-15/dbtng-tablesort-with-joins-any

I need to do an innerJoin() which appears to be a method of the SelectQuery class, and not necessarily a method of the Tablesort class. That's why the docs I see about extenders say it's critical to invoke the TableSort in the instantiation of the db\_select object. Thus, my attempt:

```
$get_all_members = db_select('users', 'u')->innerJoin('members', 'm', 'u.uid = m.uid')->extend('TableSort');

```

> Call to a member function extend() on string

is the response. Is there a way to convert a db\_query into a TableSort object like it appears the extender is doing?

Or, could I find a way to combine the fields I need in these two tables to pass to the TableSort object?

# Answer
> 1 votes
The issue is addressed in the thread you referenced. Not all methods for the select class return the new query object. In particular, `innerJoin()` returns an alias string, not the query object.

Assign your query object so you can reference it outside of the method being called:

```
$query = db_select('users', 'u')->extend('TableSort')
$query->innerJoin('members', 'm', 'u.uid = m.uid');
//@TODO: add ->fields() ->execute() etc...

```

---
Tags: 7
---


# Question
Title: Getting 443 Forbidden Error on my custom module
I am learning drupal 8 and creating my own custom module. I have a clean localhost installation and was following some tutorials online to create a very basic "hello" for my first attempt.

The issue I am running into is when I attempt to go to my routing area, I get the following error:

```
Forbidden
You don't have permission to access /tag on this server.

```

Here is my code. Can someone tell me why this isn't working? If I followed the online tutorials right, I should have access.

*tagnbag.info.yml file:*

```
name: Tag N Bag
description: 'Create a custom grocery list.'
type: module
package: Custom
version: 1.0
core: 8.x

```

*tagnbag.routing.yml:*

```
tagnbag:
  path: '/tag'
  defaults:
    _controller: 'Drupal\tagnbag\Controller\TagBagController::welcome'
    _title: 'Hello Tag N Bag!'
    requirements:
      _permission: 'TRUE'

```

*TagBagController.php:*

```
<?php
/**
 * @file
 * Contains \Drupal\tagnbag\Controller\TagBagController.
 */

namespace Drupal\tagnbag\Controller;
use Drupal\Core\Controller\ControllerBase;

class TagBagController extends ControllerBase {
    public function welcome() {
        return array(
            '#type' => 'markup',
            '#markup' => 'Content for Tag N Bag.'
        );
    }
}

```

# Answer
`_permission: 'TRUE'` is not a thing unless you've defined a custom permission `TRUE` (and if you did, I'd advise you to change that). What you have is looking to see if a user has the permission `TRUE` \- which I doubt any user has, and correctly denying access. If you want to grant access to the route for everyone, in all contexts, use `_access: 'TRUE'`. See Structure of Routes on d.o for more info.
> 0 votes

# Answer
You missing `\` in `'Drupal\tagnbag\Controller\TagBagController::welcome'` change *tagnbag.routing.yml* by:

```
tagnbag.tagnbag:
  path: '/tag'
  defaults:
    _controller: '\Drupal\tagnbag\Controller\TagBagController::welcome'
    _title: 'Hello Tag N Bag!'
  requirements:
    _access: 'TRUE'

```
> -1 votes

---
Tags: 8, routes
---


# Question
Title: How to retrieve value of hidden field in twig?
How to retrieve value of hidden field in twig?

PFB screenshot:

I am able to retrieve value of "Partition Count" field when not disabled. But not able to retrieve it's value when disabled.

Exact requirement: 1) If "Partition Count" field is **Disabled** from Drupal Admin, then field **should not be displayed**. **But this value needs to be retrieved in twig file** as display of "Reference Paragraph" will vary according to the value of "Partition Count".

2) If "Partition Count" field is **Enabled** from Drupal Admin, then field should be **displayed**. In this case, I am able to retrieve "Partition Count" field value in twig file.

---

paragraph.html.twig:: https://github.com/WondrousLLC/paragraphs\_starter\_pack/blob/master/template/paragraph/paragraph.html.twig

# Answer
The variables in a paragraph template contain the fully loaded paragraph entity:

*paragraph.html.twig*

```
{#
/**
 * @file
 * Default theme implementation to display a paragraph.
 *
 * Available variables:
 * - paragraph: Full paragraph entity.

```

from which you can retrieve raw values of any field, not matter whether base field or configured field or displayed or not:

```
{% set value = paragraph.field_example.value %}

```

On the contrary `{{ content }}`

```
 * - content: All paragraph items. Use {{ content }} to print them all,
 *   or print a subset such as {{ content.field_example }}. Use
 *   {{ content|without('field_example') }} to temporarily suppress the printing
 *   of a given child element.

```

contains only the fields configured to be displayed in "Manage Display".
> 1 votes

---
Tags: 8, theming, paragraphs
---


# Question
Title: Is there any way to create a discount that only discounts one product in an order?
We have a Drupal 7 site using Commerce and Discounts and we need to create a discount that will discount one product in the order by 100%.

Basically, we need to give a coupon discount for ONE free product but so far we only see a way to discount ALL products on the order or the entire order.

We've tried Commerce Discount EXTRA (module) and it gets close by using the "Per Quantity Product Discount" but it forces you to select one specific product that the discount would apply to instead of ANY product.

So, does anyone know of a way to achieve creating a discount to only discount ONE of ANY product in an order?

# Answer
> 1 votes
With the offer types defined in Commerce Discount / Commerce Discount Extra, there isn't much you can do. The closest ones to what you've described are the per-quantity % off discounts, but as you've discovered, you have to specify either a target product or product category. If you're using a taxonomy configuration that allows the per-quantity category discount (i.e. you have a term reference field on your product display nodes that you can target in the "Products in these offer categories" field), then you can configure this by just identifying every product category in a comma separated list. Otherwise this is going to require custom code.

Since your requirement is also to tie this to a coupon code, you're going to have to write that custom code as a custom offer type. It could be that you simply copy the per-quantiy product discount and change the matching logic to allow discounting any product on the order, but I gotta be honest ... that code is *hairy*. I wrote the current implementation, and I'm sure it would take even me a full day just to remember what's going on in there and try out some potential solutions.

That said, you could try to "hack" it using existing pieces. Basically ... you could create a new taxonomy vocabulary with a term that identifies products that are eligible for the free product offer. You can then add a term reference to that vocabulary on every product display and select the term for them. You're basically creating a global product category that all of your products are assigned to ... and you can then hide the term from the UI so customers never see it. This may actually be a preferable solution in the future anyways, as the merchant may end up wanting to restrict certain products from these coupons. Give it a go, let us know how it turned out!

---
Tags: 7, commerce
---


# Question
Title: How do I get the username from the user ID?
I want to print the username knowing just the user ID. How do I achieve this?

# Answer
> 25 votes
You can use user\_load or `\Drupal\user\Entity\User::load` to do this. Below code will provide the solution

```
 public function content() {
     $account = \Drupal\user\Entity\User::load('uid'); // pass your uid
     $name = $account->getUsername();
     drupal_set_message($name);
 }

```

`$name` gives the username of the user.

# Answer
> 7 votes
In D8, if you don't know the uid, you can do this:

```
function test_user_login(\Drupal\Core\Session\AccountInterface $account) {
   $account = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
   $user = $account->get('name')->value;
   drupal_set_message($user, 'status'); }

```

# Answer
> 1 votes
There are several ways to get the user's name programmatically

```
$account = \Drupal\user\Entity\User::load(1); // pass your uid
//1
drupal_set_message($account->name->value);
//2
drupal_set_message($account->get("name")->value);
//3
drupal_set_message($account->getUsername());
//4
drupal_set_message($account->name->getValue()[0][value]);

```

# Answer
> 0 votes
You can use `user_load($uid);` This will return a fully loaded User object(in D7).

```
$user = user_load($uid);
print $user->name;

```

This should print the user name.

---
Tags: users, 8
---


# Question
Title: Associate Every Displayed User Name With Corresponding users.data Table Row
**Updated:**

I would like data from the `users.data` table displayed with every "User Name" however it is displayed.

As an example, I have this in `hook_preprocess_page_title()`:

```
function hook_preprocess_page_title(&$variables) {

  if (\Drupal::routeMatch()->getRouteName() == 'entity.user.canonical') {

    $gUD = \Drupal::service('user.data');
    $routeUID = \Drupal::routeMatch()->getRawParameter('user');
    $gudValue = $gUD->get('module', $routeUID, 'name');

    if ($gudValue = $moduleValue)) {
      kpr('Success!');
    }

  }

}

```

The route `entity.user.canonical` allows me to reference the viewed user, and so I can use `\Drupal::routeMatch()->getRawParameter('user')` to get the non-current user ID. (it's not the route that counts, but my ability to reference the `users.data` table for the displayed user)

And this in `hook_preprocess_username()`:

```
function hook_preprocess_username(&$variables) {
  $gUD = getUsersData();
  $gudValue = $gUD->get('module', $variables['uid'], 'name');
}

```

So what I am looking for is something like:

```
hook_preprocess_HOOK() {
  $UID = // From displayed user name.
  \Drupal::service('user.data')->get('module', $UID, 'name');
}

```

for each displayed user name.

The problem here: get user id from username or email without logging in, is that I don't know, and cannot manually enter the username value.

---

A couple of examples where the username is displayed on a page without using the `username` field:

1. Views field Name (not linked to user, uses `views field` base)
2. User type entity reference field (format display `label`, uses `field` base)

`hook_preprocess_page_title()` and `hook_preprocess_username()` are pretty straight-forward. And I believe I know where/when this template/hook will be used, but I am still having trouble defining a couple of other instances, and determining the best hook to alter the output as needed.

# Answer
It sounds like you should start with what you don't want.

`Drupal::currentUser()->id()` will retrieve the current user's UID. From there, you can use the `UserStorage::loadByProperties()` method you referenced to pull the UID by user name. The last step is add code to check `Drupal::currentUser()->id()` doesn't match the UID found from `UserStorage::loadByProperties()`
> 1 votes

---
Tags: 8, users
---


# Question
Title: in views, how to get the replacement pattern of the URL of the link field
using the Link module, i have created a view of content fields:

* Link
* Title
* Body

And i want the Title to be a clickable link to the URL of the Link field. In D7 the links field provided for a replacement pattern for the URL as raw value but in D8 that is not available. How can I make the Title field a clickable link with the Link URL?

# Answer
> 6 votes
The raw replacement pattern isn't available, but you can customize a new hidden field to be the replacement equivalent:

* Add a new link field
    + Check the **Exclude from display**, **URL only**, **Show URL as plain text** options to have your field be available.
* Add a new title field
    + Uncheck **Link to the Content**
    + Use `<a href="{{ field_MY_LINK_FIELD }}">{{ title }}</a>` in the rewrite options to render title field with a link to your link field URL

---
Tags: views, 8
---


# Question
Title: Remove library from page based on node field value
We have a content type, `Basic Page`, where we may want to include 3rd party CSS such as `Bootstrap`. However, this 3rd party CSS may conflict with our custom theme, `mytheme`. On the `Basic Page`, we added a custom field of type Boolean, `field_include_css`, that a content editor can set to true if they want to use the `Bootstrap` CSS instead of `mytheme`.

**How would we remove all the libraries added to the page that come from `mytheme`?**

Here is what we tried, but did not work.

```
function mytheme_preprocess_page(&$variables) {
  $node = $variables['node']'
  // Basic page's machine name is page.
  if(is_object($node) && $node->getType() == 'page' && $node->field_include_css->value == '1') {
    unset($variables['page']['#attached']['library']);

    // above line didn't work so we also tried these, but they failed too.
    $variables['page']['#attached']['library'] = '';
    $variables['#attached']['library'] = '';
    unset($variables['#attached']['library']);
  }
}

```

# Answer
> 2 votes
Drupal has dedicated theme hook, `hook_page_attachments_alter`, for this scenario. Your theme can hook into it, check the rendered route (for your node type), and take action on the `$page['#attached']['library']` render array accordingly:

```
function MYTHEME_page_attachments_alter(array &$page) {
  $node = \Drupal::routeMatch()->getParameter('node');
  if (!is_null($node) && $node->getType() == 'page') {
    //@TODO: remove the appropriate library items from $page['#attached']['library']
  }
}

```

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


# Question
Title: How to add variables in *.libraries.yml in drupal 8
I need to convert the below code added in hook\_page\_attachments() and
add the external js in \*.libraries.yml but not sure how to add variables like
$token and $user-\>mail in the \*.libraries.yml so I can just attach library

```
   drupal_add_js('http://js.acobot.com/' . check_plain($token) . '.js', 'external');
    $script = 'var _aco = _aco || [];';
    drupal_add_js($script, array('type' => 'inline', 'scope' => 'footer'));
    if ($user->uid) {
      $user_info = "_aco.push(['email', '" . check_plain($user->mail) . "']);";
      drupal_add_js($user_info, array('type' => 'inline', 'scope' => 'footer'));
    }

```

Add Your Script to a file In \*.libraries.yml, I have added

```
acobot-initialise:
  version: 1.x
  js:
    js/acobot.js: {}
  dependencies:
    - core/jquery
    - core/drupalSettings

```

Added that file to the library under

> $attachments\['#attached'\]\['library'\]\[\] = 'acobot/acobot-initialise';

Use drupalSettings to pass data from php to js

```
  $attachments['#attached']['drupalSettings']['acobot']['email'] = check_plain($account->getEmail());

```

Added script acobot.js as follows

> (function ($, Drupal, drupalSettings) {
>
> 'use strict';
>
> Drupal.behaviors.acobot = { attach: function (context, settings) { var \_aco = \_aco || \[\]; \_aco.push(\['email', drupalSettings.acobot.email\]);
> } };
>
> })(jQuery, Drupal, drupalSettings);

# Answer
First add your acobot script inline:

```
function mymodule_page_attachments(array &$attachments) {
  $attachments['#attached']['html_head'][] = [
    // The data.
    [
      '#type' => 'html_tag',
      // The HTML tag to add, in this case a  tag.
      '#tag' => 'script',
      // The value of the HTML tag, here we want to end up with
      // alert("Hello world!");.
      '#value' => 'alert("Hello world!");',
      // Set attributes like src to load a file.
      '#attributes' => array('src' => 'http://js.acobot.com/' . check_plain($token) . '.js'),

    ],
    // A key, to make it possible to recognize this HTML  element when altering.
    'hello-world',
  ];
}

```

next add your library with \*.js file where you can call push method

```
cuddly-slider:
  version: 1.x
  js:
    js/cuddly-slider.js: {}
  dependencies:
    - core/jquery
    - core/drupalSettings

```

and pass user mail to drupalSettings.

```
$build['#attached']['drupalSettings']['fluffiness']['cuddlySlider']['foo'] = 'user mail here';

```

All examples are available here https://www.drupal.org/docs/8/creating-custom-modules/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-module
> 2 votes

# Answer
The biggest issue I see here is the hyphen in your library name. I haven't figured out how to escape the hyphen in the library name when passing the name of a library to drupalSettings so I will instead use an underscore or join the words. In this case the library name would be acobot\_initialise or acobotinitialise. In this example use the underscore so to begin, change your library name to acobot\_initialise.

You need to add your variable(s) to drupalSettings and that is done in the preprocess of the entity you are working with. It could be a node or a paragraph or some other entity in which case you'll use hook\_preprocess() in your\_module.module file. In your example, it would look like the following:

```
function mymodule_preprocess(&$variables, $hook, $info) {
  // Add code to expose $account->getEmail() to this code block
  $computed_settings = [
    "acobotemail" => check_plain($account->getEmail());,
    "anothervariable" => "a variable you want to pass to the js file";,
  ];
  $build['#attached']['library'][] = 'acobot/acobot_initialise';
  $build['#attached']['drupalSettings']['acobot']['acobot_initialise'] = $computed_settings;
}

```

Then you need to expose drupalSettings to your JS file, acobot.js. You will do this as follows:

```
(function ($, Drupal, drupalSettings) {
  Drupal.behaviors.Acobot = {
    attach: function (context, settings) {
      var acobotemail = drupalSettings.acobot.acobot_initialise.acobotemail;
      var anothervariable = drupalSettings.acobot.acobot_initialise.anothervariable;
      // Do Some stuff with the variables acobotemail and anothervariable.
    }
  }
})(jQuery, Drupal, drupalSettings);

```
> 1 votes

---
Tags: 8
---


title: Paragraphs from sub_process

text:
# Question
Title: Paragraphs from sub_process
I need to migrate a json feed with following example structure;

```

{
   "data":[
      {
         "id":"11028",
         "first_name":"Foo",
         "last_name":"Bar",
         "functions":{
            "group_function":{
               "data":[
                  {
                     "group":"1",
                     "function":"Scrummaster",
                     "active":"1"
                  },
                  {
                     "group":"2",
                     "function":"Developer",
                     "active":"0"
                  }
               ]
            }
         }
      },
      {
         "id":"11029",
         "first_name":"John",
         "last_name":"Doe",
         "functions":{
            "group_function":{
               "data":[
                  {
                     "group":"1",
                     "function":"Project manager",
                     "active":"1"
                  },
                  {
                     "group":"2",
                     "function":"Project owner",
                     "active":"1"
                  }
               ]
            }
         }
      }
   ]
}

```

For this, I was thinking of having a teammember node, and a teamfunction paragraph type for the functions for each team member.

If i understand migrate api correctly, i create 2 migrations for this. One for the node and one for the paragraphs.

How can I iterate over the group\_function/data array within my paragraphs migration?

I tried:

```

source:
  plugin: url
  data_fetcher_plugin: http
  data_parser_plugin: json
  headers:
    Accept: 'application/json; charset=utf-8'
    Content-Type: 'application/json'
  urls: example.com/team.json
  item_selector: data/functions

```

But I get following response on a 'drush ms':
**Could not retrieve source count from team\_function: Passed variable is not an array or object**

How would you do this?

# Answer
> 4 votes
You could also create a process plugin to create the Paragraph inline with the record you are migrating. I can't do piecemeal migrations in my case. The project has about 100,000 nodes and no data structure to 'create' Paragraphs out of. Even if I could, I don't want to have to run that dozens of times to get a full set of data.

Anyway.

Here is a real example:

```
<?php

namespace Drupal\mymodule_migration\Plugin\migrate\process;

use Drupal\migrate\ProcessPluginBase;
use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\Row;
use Drupal\paragraphs\Entity\Paragraph;

/**
 * @MigrateProcessPlugin(
 *   id = "published_author_paragraph_item",
 *   handle_multiples = TRUE
 * )
 */
class PublishedAuthorParagraphItem extends ProcessPluginBase {

  /**
   * {@inheritdoc}
   */
  public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
    $paragraphs = [];

    foreach ($value as $item) {
      $paragraphs[] = $this->createParagraphItem($item);
    }

    return $paragraphs;
  }

  /**
   * {@inheritdoc}
   */
  public function multiple() : bool {
    return TRUE;
  }

  /**
   * Generates a paragraph item entity.
   *
   * @param array $value
   * @return array
   * @throws \Drupal\Core\Entity\EntityStorageException
   * @throws \Drupal\migrate\MigrateException
   */
  protected function createParagraphItem(array $value) : array {
    $paragraph = Paragraph::create([
      'type' => 'paper_authors',
      'field_paper_author' => [
        'target_id'  =>  $value['user_id'],
      ],
      'field_paper_published_name' => [
        'value'  =>  $value['name'],
      ],
      'field_paper_disclosure' => [
        'value'  =>  $value['disclosure'],
        'format' => 'basic_html',
      ],
    ]);

    $paragraph->save();

    return [
      'target_id' => $paragraph->id(),
      'target_revision_id' => $paragraph->getRevisionId(),
    ];
  }
}

```

In my migration definition yaml:

```
  _authors_shim:
    plugin: generate_authors_array
    source: author_array
  field_paper_published_authors:
    plugin: published_author_paragraph_item
    source: '@_authors_shim'

```

`generate_authors_array` is another process plugin I use to massage the data for the plugin code above. This paragraph type has a user reference, a plain text field and long text field. The passed value is an array of arrays, so this will in fact create multiple paragraph deltas for the paragraph field I am filling. It also rolls back properly.

I had tried to get this to work with `sub_process` at first, but could not get the paragraph field to populate at all until I went this route. I believe this is due to paragraph fields hold references to their stored entities (target\_id, target\_revision\_id).

---
Tags: migrations, 8
---


# Question
Title: Views issue: How to pull content from two different taxonomy vocabularies on same page
I have two Content types: Article1 with **vocabulary1** with taxonomy terms: A, B, news; Article2 with **vocabulary2** with taxonomy terms: X, Y, news.

I need to create a /news view page that displays content from both Article1 and Article2 tagged with "news".

I tried to use Filter Criteria: Has taxonomy term - vocabulary1 -\> news OR Has taxonomy term - vocabulary2 -\> news Nothing shows.

Please note that I set up Pathauto to publish in /news/article\_title both Article1 and Article2 tagged with "news". Maybe a contextual filter could be used to pull all content from /news/\*?

Thanks in advance, Cosmin

# Answer
> 0 votes
I tried it myself and *views filter OR group* is not working.

I think you just hit on a known bug.

Follow the discussion in this issue and this one and apply the latest patches mentioned and see if you can make it work. Make sure that you post back with your experience (did it work or not) so you can help this issue move along and eventually make it into a release.

**As a workaround** consider using 1 vocabulary (instead of 2) that holds all terms and your views filtering does not need an *OR group*.

---
Tags: views
---


title: How do I activate Google Custom Search?

text:
# Question
Title: How do I activate Google Custom Search?
I've just installed the Google Custom Search Module.

I've activated the module and inserted the API. The search is is till not working.

Something I'm missing?

Note: I've realized I need the paid version. is there a free Google Custom Search, free option?

# Answer
> 4 votes
As you can read in `README.txt` file:

```
*** About Google Site Search module
---------------------------------------
This requires "Site Search Edition" (paid version of Google's Custom Search).

```

You need to have a paid Google Site Search engine, so you can receive results in custom format (e.g. XML).

If you've free version, check the alternatives modules such as: Google Search Appliance or Google Custom Search Engine. Or use alternative services such as Yahoo YQL (e.g. YQL Views).

# Answer
> 1 votes
For those who are still searching for a free solution - you could try the Simple Google Custom Search Engine module. I have been using these on production sites without any issues.

> Provides integration with Google's Custom Search Engine.

**Note:** I am one of the maintainers of the module. Please feel free to report any issues in the issue queue.

---
Tags: 7, search
---


# Question
Title: What does Drush error "Unknown option: --db-url" mean?
Somehow user 1 has become blocked on a Drupal site I manage. As a result, I can't issue a uli command via Drush. I tried to use the command

```
drush @pantheon.xxxxxx.dev user-unblock --uid=1

```

but it returns error

```
Unknown option: --db-url.  See `drush help user-unblock` for available options.

```

I have checked the help for user-unblock for but it does not mention --db-url. The site is working and and other users can log in, however I can't get in as admin.

Thanks.

# Answer
Pantheon site aliases are only compatible with Drush 5. I had the same message when trying to use Drush 6.

On a Mac with Homebrew, I ran "brew install drush5" and then symlinked the resulting file (/usr/local/Cellar/drush5/5.9/libexec/drush) to "/usr/local/bin/drush5" not to interfere with my existing Drush installation.

Now I can run commands such as "$ drush5 @pantheon.xxx uli" when needed for Pantheon.
> 3 votes

# Answer
incase someone is trying to add -- to other drush commands you can use:

terminus drush site.env -- \[drush command here\] -- \[drush option here\]

the "--" after the site.env will pass the options to drush instead of terminus.

example: terminus drush $SITE\_ID -- up -s --security-only
> 3 votes

# Answer
As of this writing, Pantheon site aliases are only compatible with Drush 5.

If you're using a newer version of Drush (6, 7, 8+), you'll likely get the following message when trying to execute a Drush command with a Pantheon alias:

```
$ drush @pantheon.xxx.xxx status

Unknown option: --db-url. See `drush help pm-enable` for available [error]
options. To suppress this error, add the option --strict=0.

```

There are two possible workarounds:

1. Provide the option `--strict=0` to each Drush command

`$ drush @pantheon.xxx.xxx status --strict=0`
2. Install Drush 5 and use it specifically with Pantheon

If you're a Mac user and use Homebrew, the second option is as simple as:

`$ brew install drush5`

`$ ln -s /usr/local/Cellar/drush5/5.9/libexec/drush /usr/local/bin/drush5`

`$ drush5 @pantheon.xxx.xxx user-login`

The first method works for me using Drush 8.1.9 and Drupal 7.53 (and optionally Terminus 1.0.0) on macOS 10.12.3 "Sierra". I have not personally tested the second method.

*In either case, be sure your Pantheon aliases are up-to-date:*

```
$ terminus aliases
[notice] Aliases file written to ~/.drush/pantheon.aliases.drushrc.php

```
> 2 votes

# Answer
Have you tried fixing it directly in the database? You should be able to `update users set status = 1 where uid = 1;`

If for whatever reason you cant do this, you can try running the query with drush: `drush sql-query "update users set status = 1 where uid = 1"`
> 0 votes

---
Tags: drush
---


# Question
Title: How to get the View Object from ViewsBlock?
I'm loading a variable list of blocks. In some cases these blocks are a views\_block type. When I load a views\_block, the viewsblockbase provides the protected View object, but does not provide a method to retrieve it.

How would I go about retrieving the full view object from a views\_block?

I considered a ViewsBlock::Create() approach however this would be redundant which Im trying to avoid. Likewise, I have the view\_id and display\_id but would rather not Views::GetView() when the object is already sitting right there in the loaded block.

snippet

```
<?php

public function buildDashboard() {
  // $block_instance = new DashboardBlockManager;
  $block_instance = \Drupal::service('plugin.manager.block');
  $blocks = $this->getBlocks();
  foreach ($blocks as $region => $region_blocks) {
    foreach ($region_blocks as $index => $block_id) {

      //$block_id example views_block:dashboard_tasks_by_assignee-block_1

      $load_block = $block_instance->createInstance($block_id);

      $title = $load_block->label();
      $build_block = $load_block->build();
      $build_block['#block_title'] = $title;

      //check the plugin type
      $definition = $load_block->getPluginDefinition();

      if ($definition['id'] == 'views_block') {
        //cant do this
          $view = $load_block->view;
      }
}

```

# Answer
I think there is no way to get the the view Object directly it's protected property and there is no method to get it: From ViewsBlockBase

> /\**
> * The View executable object.
> *
> * @var \Drupal\views\ViewExecutable
> \*/
> protected $view;

But there is a way first get the view id from the `DerivativeId` and then load the view here is a code snippet below:

```
  use Drupal\views\ViewExecutable;

  $blockManager = \Drupal::service('plugin.manager.block');
  $contextRepository = \Drupal::service('context.repository');
  // Get blocks definition.
  $definitions = $blockManager->getDefinitionsForContexts($contextRepository->getAvailableContexts());
  $views_blocks = [];
  foreach ($definitions as $id => $definition) {
    $id_type = explode(':', $id);
    if ($id_type[0] == 'views_block') {
      /** @var \Drupal\views\Plugin\Block\ViewsBlock $viewsBlock */
      $viewsBlock = $blockManager->createInstance($id);
      $derivativeId = $viewsBlock->getDerivativeId();
      $derivativeId_exploded = explode('-', $derivativeId);
      $view_id = $derivativeId_exploded[0];
      $view = Views::getView($view_id);
      $views_blocks[] = $view;
    }
  }

```

I hope that helps.
> 0 votes

---
Tags: views, 8, blocks
---


title: Download file programmatically

text:
# Question
Title: Download file programmatically
I have a custom module where I need to create a file and download it on form submission. So far, I managed to created the file and save it in public folder, but I cannot find a way to download it to client. This is the code I wrote so far.

```
public function submitForm(array &$form, FormStateInterface $form_state) {
  $file_name = $date.'-event.ics';
  $cal_file = file_unmanaged_save_data('file content',"public://cal/$file_name",FILE_EXISTS_RENAME);
  return new RedirectResponse(file_create_url("public://cal/211443-event.ics"));
}

```

# Answer
You can return a BinaryFileResponse from a controller, or as 4k4 has added:

```
$response = new BinaryFileResponse("public://cal/211443-event.ics");
$form_state->setResponse($response);

```
> 5 votes

# Answer
That is what, for example, the `Drupal\locale\Form\ExportForm` class does. See the code used in `ExportForm::submitForm()`.

```
$response = new BinaryFileResponse($uri);
$response->setContentDisposition('attachment', $filename);
$form_state->setResponse($response);

```

`$response->setContentDisposition()` sets the *Content-Disposition* header with the given filename. That is the filename used for the *Save file* dialog the browser will show to users.
> 2 votes

---
Tags: forms, files
---


# Question
Title: How can I check if the cart has shippable products?
How can I check if the cart has any shippable product in Ubercart 3 for Drupal 8? Previous version had `uc_cart_is_shippable()` method which Drupal 8 module does not seem to have by default.

Is there a separate/additional module to get this function working? Or how else can I check if the cart has a shippable product?

# Answer
The function is now a part of the `CartInterface` and implemented in the `Cart::isShippable()` method. You can use the `CartManager` service to retrieve the `Cart` object and call the method:

```
\Drupal::service('uc_cart.manager')->get()->isShippable()

```
> 1 votes

---
Tags: 8, ubercart
---


# Question
Title: Alter field instance settings form on admin/structure/types/manage/<content type>/fields/node.<content type>.<fieldname>/storage
I'm trying to figure out how to add an extra field to content type field settings page.

Basically I want to alter field instance settings form on **admin/structure/types/manage//fields/node../storage** .

I'm going with **hook\_form\_FORM\_ID\_alter for FORM\_ID field\_config\_edit\_form**. The new form element appears on the form but after submit I'm not able to see the value.

Am I missing something? Is an extra form submit function required other than the default one to submit my new value?

Here is my snippet -

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function mymod_form_field_storage_config_edit_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

  $form['enabled'] = array(
      '#type' => 'checkbox',
      '#title' => t('Enable'),
      '#description' => t('If enabled then this module will alter the field settings.'),
      '#default_value' => $form['enabled'],
  );
}

```

# Answer
> 0 votes
Here is an example -

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function mymod_form_field_storage_config_edit_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

  $form['enabled'] = array(
      '#type' => 'checkbox',
      '#title' => t('Enable'),
      '#description' => t('If enabled then this module will alter the field settings.'),
      '#default_value' => $form['enabled'],
  );

  $form['#entity_builders'][] = '_my_additional_form_field_storage_submit';
}

/**
 * Entity builder.
 */
function _my_additional_form_field_storage_submit($entity_type, Drupal\field\Entity\FieldStorageConfig $fieldStorageConfig, &$form, \Drupal\Core\Form\FormStateInterface $form_state) {

  if ($form_state->getValue('enabled')) {
    $fieldStorageConfig->setThirdPartySetting('my_additional_settings', 'enabled', $form_state->getValue('enabled'));
  }
  return true;
}

```

---
Tags: 8, entities
---


# Question
Title: How to get vocabularies for an entity reference to a taxonomy?
So I'm having a bit of a difficult time finding out how to get the information I want.

I have an entity reference field - call it `field_event_type`. This is an entity reference to a taxonomy. I am trying to programmatically get the possible vocabularies associated with this entity reference and get the fields/properties associated with them. Basically walking each of the bundles to get their relevant information.

So far I can get the field definition on the parent node, which looks like this:

```
Array
(
    [uuid] => 32eeda5f-270f-477d-b24c-75ed15e69b2a
    [langcode] => en
    [status] => 1
    [dependencies] => Array
        (
            [module] => Array
                (
                    [0] => node
                    [1] => taxonomy
                )

        )

    [id] => node.field_event_type
    [field_name] => field_event_type
    [entity_type] => node
    [type] => entity_reference
    [settings] => Array
        (
            [target_type] => taxonomy_term
        )

    [module] => core
    [locked] =>
    [cardinality] => 1
    [translatable] => 1
    [indexes] => Array
        (
        )

    [persist_with_no_fields] =>
    [custom_storage] =>
)

```

By doing this:

```
\Drupal::config('field.storage.node.field_event_type')->get();

```

Based on this link:

field\_info\_field() deprecated, what's the equivalent?

But I'm not sure how to get the vocabularies or even if that's the right thing to do to get the information I want.

How would I go about getting the vocabularies? I should be able to just load by VID and get the correct fields at that point, correct?

# Answer
> 1 votes
I too was trying to sort out how to get the vocabulary from the entity reference field for a node type. Here's code that seems to work for me - returns an array keyed on fieldname with vocabulary as the value. I check out the field handler and flag ones with "default:taxonomy" as taxonomy reference fields. Then I loop through dependencies\['config'\] to see if taxonomy.vocabulary is referenced and get the value.

```
$bundle = 'page';
$vocs = [];
$flds = \Drupal::service('entity_field.manager')
  ->getFieldDefinitions('node', $bundle);
foreach ($flds as $fld) {
  $hand = $fld->getSettings()['handler'];
  if ($hand == "default:taxonomy_term") {
    $fldnm = $fld->getName();
    $config = $fld->get('dependencies')['config'];
    foreach($config as $cf){
      if(strpos($cf,"taxonomy.vocabulary") !== FALSE){
        $vocs[$fldnm] = str_replace("taxonomy.vocabulary.","",$cf);
      }
    }
  }
}
dpm($vocs);

```

# Answer
> 0 votes
So here is my process (it won't work when you're loading in the relevant entity types via a view, only by the "default" method):

`$type` is the content type, `$field` is the field of the ER.

$field\_data = \Drupal::config('field.field.node.' . $type . "." . $field)-\>get();

$bundles = $field\_data\['settings'\]\['handler\_settings'\]\['target\_bundles'\];

At which point you can iterate over the given bundles for an ER.

You'll probably want to do some flow control somewhere to ensure the ER has the correct handler you want - located here:

```
$handler = $field_data['settings']['handler'];

```

But this should work to get the data I asked for above.

# Answer
> 0 votes
You can also see the structure from config file Filename: field.field.node.article.field\_tags.yml

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


# Question
Title: How to solve Mysql PDOException: SQLSTATE[42S02]: Base table or view not found:
I have created form to add general information about daily work. When I submit this form it will give me following error. Please help me. I have checked my `setting.php`. There prefix is `drup_`

> PDOException: SQLSTATE\[42S02\]: Base table or view not found: 1146 Table 'i1164525\_drup1.drup\_drup\_Detailstable' doesn't exist: INSERT INTO {drup\_Detailstable} (Username, Email\_Id, Work\_Location,Team\_size,Total\_hours,Date,Description,Verified) VALUES ('admin','swap@mm.com','abc','1','20','12/12/2014','Test','Not Verified'); Array ( ) in eval() (line 43 of /home/csrdiarycom/public\_html/modules/php/php.module(80) : eval()'d code).

```
 <form name="form" method="post" action=''<?php echo $_SERVER['PHP_SELF']; ?>">
 <label>Work Location</label>
 <input type="Text" name="location" value=""/>
 <label>Individual/ Number of people</label>
 <input type="Text" name="numberofpeople" value=""/>
 <label>Date</label>
 <input type="Text" name="date" value=""/>
 <label>Total Time spend by You/Team(In Hours)</label>
 <input type="Text" name="Totalhours" value=""/>
 <label>Your Experience</label>
 <textarea row="5" maxlength="200" cols="30%" name="comment">Type here</textarea>
 <input type="Submit" name='Submit'/></form>
 <?php
 if(isset($_POST['Submit']))
 {
   $location=$_POST['location'];
   $numberofpeople=$_POST['numberofpeople'];
   $Totalhours=$_POST['Totalhours'];
   $date=$_POST['date'];
   $comment=$_POST['comment'];
   db_query("INSERT INTO {drup_Detailstable} (Username, Email_Id, Work_Location,Team_size,Total_hours,Date,Description,Verified) VALUES ('$e','$e','$location','$numberofpeople','$Totalhours','$date','$comment','Not Verified')")->execute();
  echo "<h2>Thank you for your Comment!</h2>";
  }}
  ?>

```

# Answer
> 1 votes
Remove the 'drup\_' prefix from your db\_query call. Since you define a prefix in settings.php, using {Detailstable} will automatically add the prefix on lookup.

# Answer
> 0 votes
This can be done from phpmyadmin or drush.

**drush sql-cli**

> mysql\> DELETE FROM field\_config WHERE field\_name = \[‘field\_DELETED\_FIELD’\];
>
> mysql\> DELETE FROM field\_config\_instance WHERE field\_name = \[‘field\_DELETED\_FIELD’\];

Clear cache after deleting i.e. drush cc all

---
Tags: forms
---


# Question
Title: How to trace an Error: PDOException: SQLSTATE[23000]:
I'm trying to trace this error which is shown when I save a new **basic page** node.

It seems to me that I am trying to save a duplicated title value in **field\_data\_title\_field**, but it doesn't make any sense to me. I found this question PDOException: SQLSTATE\[23000\]: Integrity constraint violation: 1062 Duplicate entry '1532856' for key 'PRIMARY': INSERT INTO {watchdog} but it was related to dblog table (Watchdog module). Mine is related to: **modules/field/modules/field\_sql\_storage/field\_sql\_storage.module**

Drupal core is updated to last version.

How can I trace and fix this?

ERROR:

> PDOException: SQLSTATE\[23000\]: Integrity constraint violation: 1062 Duplicate entry 'node-4294967295-0-0-und' for key 'PRIMARY': INSERT INTO {field\_data\_title\_field} (entity\_type, entity\_id, revision\_id, bundle, delta, language, title\_field\_value, title\_field\_format) 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); Array ( \[:db\_insert\_placeholder\_0\] =\> node \[:db\_insert\_placeholder\_1\] =\> 4294967295 \[:db\_insert\_placeholder\_2\] =\> 3187 \[:db\_insert\_placeholder\_3\] =\> page \[:db\_insert\_placeholder\_4\] =\> 0 \[:db\_insert\_placeholder\_5\] =\> und \[:db\_insert\_placeholder\_6\] =\> My node title \[:db\_insert\_placeholder\_7\] =\> ) enfield\_sql\_storage\_field\_storage\_write() (line 514 of /home/examplesite/www/modules/field/modules/field\_sql\_storage/field\_sql\_storage.module )

# Answer
The composite primary key for field tables is `entity_type`,`entity_id`,`deleted`,`delta`,`language`. The error itself lists the key:

```
'node-4294967295-0-0-und'

```

You can confirm that there is a pre-existing field in the table by querying your database with a search on those values.

Also of note, your node id is at 4294967295. This is the upper limit of 32-bit unsigned integers; anything higher than that is going to start causing problems with your SQL storage.
> 1 votes

# Answer
Since you've reached your limit for your data value in this column, the value is acting as a MAX and using the maximum value that can be stored in the column. In this case, it's already in use.
> 0 votes

---
Tags: debugging
---


# Question
Title: How do I get the list of the custom fields added to an entity?
I am trying to get the custom fields created for the *User* entity in Drupal 8.

* `Drupal::service('entity_field.manager')->getFieldStorageDefinitions('user')` returns all the fields
* `Drupal::service('entity_field.manager')->getFieldDefinitions('user', '')` returns only the default fields

My code creates the list by removing the fields returned from `getFieldDefinitions('user', '')` by the fields returned from `getFieldDefinitions('user'`.

Is there a proper way to achieve this?

# Answer
You can filter the fields by checking which interface the field implements:

```
$fields = array_filter(
  \Drupal::service('entity_field.manager')->getFieldDefinitions('user', 'user'),
  function ($fieldDefinition) {
    return $fieldDefinition instanceof \Drupal\field\FieldConfigInterface;
  }
);

```

The second parameter of getFieldDefinitions() is the bundle. The user entity doesn't have bundles, but you can configure bundle fields. In this case the bundle name defaults to the entity id.
> 4 votes

---
Tags: 8, entities
---


title: Howto theme list of nodes as item-list?

text:
# Question
Title: Howto theme list of nodes as item-list?
I want to show a block with related nodes. The function `getRelatedArticles()` is a complex one and I can't build it with views. Is it possible to use the method `viewMultiple()` and output the list as item-list? If not, what would be the best practisce becide looping over the array and build the render array for each node? Something similar to the following code (which obviously does not work):

```
class RelatedArticleBlock  extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function build() {

    $related_nids = $this->getRelatedArticles();

    $nodes = Node::loadMultiple($related_nids);
    $block['content'] = [
      '#theme' => 'item_list',
      '#list_type' => 'ul',
      '#wrapper_attributes' => [
        'class' => [
          'row',
        ],
      ],
      // I want to do something like:
      // '#items' => \Drupal::entityTypeManager()->getViewBuilder('node')->viewMultiple($nodes, 'teaser'),
    ];

    // I would like to avoid the following, build each node on it's own.
    foreach ($nodes as $node) {
      $block['content']['#items'][] = \Drupal::entityTypeManager()->getViewBuilder('node')->view($node, 'teaser');
    }

    return $block;
  }
}

```

# Answer
> 1 votes
`viewMultiple()` also optimizes the rendering process by returning a common #pre\_render callback in the build array, see the discussions and linked topics here Twig: "for" does not display variable content without first displaying all variable content, so you can't put the output directly in `#items`.

So building each node on its own is the way to go and you probably won't find any differences in performance, because both methods result in the same caching mechanism.

---
Tags: 8, theming
---


# Question
Title: how to programmatically set unpublish_on
How can I programmatically set the unpublish\_on field(scheduler module) for a node entity in drupal 7?

```
$entity = entity_metadata_wrapper('node', $node);
$entity->language(LANGUAGE_NONE);
$entity->title = 'My Title';
$entity->body->set(array(
    'value' => $body,
    'summary' => $summary,
    'format' => 'full_html',
  ));
$entity->scheduler_settings->set(array(
    '#required' => TRUE,
    '#unpublish_on' => '2018-06-25 12:23:11',
    '#date_format' => 'd.m.Y H:i:s',
  ));

```

# Answer
Follow the examples set by the scheduler module when it loads, inserts, and builds the form. Add the `unpublish_on` property to the node object with the value of the UNIX timestamp (of when it will unpublish). When the node is saved, the scheduler module will save the unpublish date.

```
$node = node_load(123);
$node->unpublish_on = strtotime("2018-06-25 12:23:11");
node_save($node);

```
> 0 votes

---
Tags: 7, entities
---


# Question
Title: How to get a field third party settings for every content entity forms
Can someone explain or post an example of how to get a third party field settings on every content entity forms?

I'm looking for a generic code where a form can be customized (like calling a custom validator) if any field present in that form is having the third party settings that I have defined.

It could be a node form, a block form, a paragraph etc.

# Answer
> 2 votes
Implement `hook_field_widget_form_alter()` to alter form elements of any content entity form.

For example how to add a validate callback when you have third party settings stored in the field configuration:

```
/**
 * Implements hook_field_widget_form_alter().
 */
function mymodule_field_widget_form_alter(&$element, FormStateInterface $form_state, $context) {
  $field_definition = $context['items']->getFieldDefinition();
  if ($field_definition instanceof \Drupal\field\FieldConfigInterface) {
    $mymodule_settings = $field_definition->getThirdPartySettings('mymodule');
    if (!empty($mymodule_settings)) {
      $element['#mymodule_settings'] = $mymodule_settings;
      $element['#element_validate'][] = 'mymodule_element_validate';
    }
  }

}

```

---
Tags: 8, entities, forms
---


title: How to create a permission with logic

text:
# Question
Title: How to create a permission with logic
I need to create a permission to allow users to see the content overview page (/admin/content) only during business hours (9 AM to 5 PM).

Drupal core comes with the "Access the Content overview page" permission; but I need "Access the Content overview page during work hours".

I know how to create a permission and how to test that the user has the permission. What I don't understand is how to assign some logic to a permission itself (for example, *within business hours*).

I can do this in mymodule.permissions.yml.

```
access content overview within business hours:
  title: 'Access the Content overview page within business hours'
  restrict access: TRUE

```

I can check the user has the permission with `\Drupal::currentUser()->hasPermission('access content overview within business hours')`.

How can I make the permission return `TRUE` only during business hours?
How can I check the permission only when the users visits the content overview page?

I can foresee multiple use cases for needing some logic implementation within the permission itself, for example when allowing/restricting access to certain pages depending on whether the environment is development or production, or allowing/restricting access depending on the value of some fields.

**\- EDIT -**

As suggested in the comments, I've started by creating the following three files on my module; but it doesn't work. The `CustomAccessChecks::access` never gets called.

File: custom\_access.services.yml

```
services:
  custom_access.route_subscriber:
    class: Drupal\custom_access\Routing\AdminRouteSubscriber
    tags:
      - { name: event_subscriber }
  custom_access.access_checker:
    class: Drupal\custom_access\Access\CustomAccessChecks
    tags:
      - { name: access_check }

```

File: src/Access/CustomAccessChecks.php

```
<?php

namespace Drupal\custom_access\Access;

use Drupal\Core\Routing\Access\AccessInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Access\AccessResultAllowed;
use Symfony\Component\Routing\Route;
use Drupal\Core\Routing\RouteMatchInterface;

class CustomAccessChecks implements AccessInterface {

  /**
   * A custom access check.
   *
   * @param \Drupal\Core\Session\AccountInterface $account
   *   Run access checks for this account.
   */
  public function access(Route $route, RouteMatchInterface $route_match, AccountInterface $account) {
    return AccessResultAllowed::allowedIf((int) $account->id() === 1);
  }
}

```

File: AdminRouteSubscriber.php

```
<?php

namespace Drupal\custom_access\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

class AdminRouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  public function alterRoutes(RouteCollection $collection) {

    if ($route = $collection->get('system.admin_content')) {
      $route->setRequirement('_custom_access', '\Drupal\custom_access\Access\CustomAccessChecks::access');
    }
  }
}

```

As expected, visiting '/admin/content' as the main administrator `$account->id() === 1` works, but when visiting as another authenticated user, I still can access the page.

What I'm missing?

# Answer
> 1 votes
When the access to a route doesn't depend uniquely on a single permission, you need to implement what Access checking on routes describes.

* Implement a service tagged *access\_check*
* Associate it with the route

Since you are altering the route defined from another module, you need to also follow Altering existing routes and adding new routes based on dynamic ones.

### example.services.yml

```
services:
  example.route_subscriber:
    class: Drupal\example\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber }

  example.access_checker:
    class: Drupal\example\Access\CustomAccessCheck
    tags:
      - { name: access_check }

```

### RouteSubscriber.php

```
namespace Drupal\example\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    if ($route = $collection->get('system.admin_content')) {
      $route->setRequirement('_custom_access', 'example.access_checker::access');
    }
  }

```

### CustomAccessCheck.php

```
namespace Drupal\example\Access;

use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Routing\Access\AccessInterface;

/**
 * Checks access for displaying configuration translation page.
 */
class CustomAccessCheck implements AccessInterface {

  /**
   * A custom access check.
   *
   * @param \Drupal\Core\Session\AccountInterface $account
   *   Run access checks for this account.
   *
   * @return \Drupal\Core\Access\AccessResultInterface
   *   The access result.
   */
  public function access(AccountInterface $account) {
    // Check permissions and combine that with any custom access checking needed. Pass forward
    // parameters from the route and/or request as needed.
    return ($account->hasPermission('access content overview within business hours') && $this->checkTimeAccess()) ? AccessResult::allowed() : AccessResult::forbidden();
  }

}

```

The `checkTimeAccess()` method I didn't write should check if the user is trying to access the route during the business hours.

I cannot tell what happens with a route using the *\_permission* requirement when it is altered to use also the *\_custom\_access* requirement. I didn't find the Drupal core code handling the access to a route, so I cannot say which requirement is used first.
I didn't also find a way to remove requirements from a route when altering it.

---
Tags: 8, users
---


# Question
Title: Site works ok but composer complains about unmet requirements. Do I have a problem?
## UPDATE: I am not going to continue to troubleshoot this. Composer is working OK in my local site, so I'm going to change my approach to deployment and stop running composer in my staging site. Instead I will run composer locally, commit core & vendor to the git project, and deploy all code to staging with git.

---

I am trying to get my permissions right, so I don't have to run composer as root. As part of this process, I deleted vendor, core and composer.lock and ran composer install with my non-root user. The site appears to be working fine, despite this message composer displayed:

```
  Problem 1
    - drupal/core 8.2.x-dev requires symfony/psr-http-message-bridge v0.2 -> satisfiable by symfony/psr-http-message-bridge[v0.2] but these conflict with your requirements or minimum-stability.
    - don't install drupal/core-render 8.2.0|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.2.0-beta1|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.2.0-beta2|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.2.0-beta3|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.2.0-rc1|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.2.0-rc2|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.2.1|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.2.2|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.2.3|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.2.4|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.2.5|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.2.6|remove drupal/drupal dev-master
    - don't install drupal/core-render 8.2.7|remove drupal/drupal dev-master

    etcetera

```

What does this mean? Is my site OK, or did I take a wrong turn?

I'm not sure why the composer message references "drupal/core 8.2.x-dev". Here is the "require" section of my composer.json:

```
"require": {
    "composer/installers": "^1.0.24",
    "wikimedia/composer-merge-plugin": "^1.4",
    "drupal/entity_clone": "^1.0@beta",
    "drupal/features": "^3.8",
    "drupal/metatag": "^1.8",
    "drupal/webform": "^5.1",
    "drupal/config_installer": "^1.8",
    "drupal/entity_browser": "^2.1",
    "drupal/media_entity_browser": "^1.0@beta",
    "drupal/entity_embed": "^1.0@beta",
    "drupal/file_browser": "^1.1",
    "drupal/admin_menu_search": "^1.0",
    "drupal/admin_toolbar": "^1.26",
    "drupal/backup_migrate": "^4.0",
    "drupal/block_field": "^1.0@alpha",
    "drupal/contact_block": "^1.4",
    "drupal/contribute": "^5.0@beta",
    "drupal/ctools": "^3.2",
    "drupal/entity_reference_revisions": "^1.6",
    "drupal/facets": "^1.3",
    "drupal/field_group": "^1.0",
    "drupal/form_placeholder": "^1.0",
    "drupal/formblock": "^1.0@beta",
    "drupal/glazed_helper": "^1.3",
    "drupal/google_analytics": "^3.0",
    "drupal/honeypot": "^1.29",
    "drupal/imce": "^1.7",
    "drupal/insert_block": "1.x-dev",
    "drupal/linkit": "^4.3",
    "drupal/login_emailusername": "^1.1",
    "drupal/material_admin": "^1.0@alpha",
    "drupal/menu_link_attributes": "^1.0",
    "drupal/minifyhtml": "^1.6",
    "drupal/paragraphs": "^1.6",
    "drupal/pathauto": "^1.3",
    "drupal/redirect": "^1.3",
    "drupal/require_login": "^2.0",
    "drupal/search_api": "^1.11",
    "drupal/simple_sitemap": "^3.0",
    "drupal/simplenews": "^1.0@alpha",
    "drupal/tfa": "^1.0@alpha",
    "drupal/token": "^1.5",
    "drupal/video_embed_field": "^2.0",
    "drupal/view_unpublished": "^1.0@alpha",
    "drupal/viewport": "^1.1",
    "drupal/viewsreference": "^1.4",
    "drupal/workflow_state_config": "^1.0@alpha",
    "drupal/xmlsitemap": "^1.0@alpha",
    "drupal/allowed_formats": "^1.1",
    "drupal/asset_injector": "^2.4",
    "drupal/taxonomy_access_fix": "^2.6",
    "drupal/text_summary_options": "^1.0",
    "drupal/migrate_source_csv": "^2.2",
    "drupal/migrate_plus": "^4.1",
    "drupal/migrate_tools": "^4.1",
    "drupal/migrate_file": "^1.1",
    "drupal/entityqueue": "^1.0@alpha",
    "drupal/module_missing_message_fixer": "^1.0@beta",
    "drupal/rules": "^3.0@alpha",
    "ckeditor/autogrow": "^4.8",
    "ckeditor/codemirror": "^1.17",
    "ckeditor/fakeobjects": "^4.8",
    "ckeditor/image": "^4.8",
    "ckeditor/link": "^4.8",
    "codemirror/codemirror": "^5.36",
    "jquery/geocomplete": "^1.7",
    "jquery/icheck": "^1.0",
    "jquery/image-picker": "^0.3.0",
    "jquery/inputmask": "^3.3",
    "jquery/intl-tel-input": "^12.1",
    "jquery/rateit": "^1.1",
    "jquery/select2": "^4.0",
    "jquery/timepicker": "^1.11",
    "jquery/toggles": "^4.0",
    "jquery/word-and-character-counter": "^2.5",
    "progress-tracker/progress-tracker": "^1.4",
    "signature_pad/signature_pad": "^2.3",
    "drupal/image_widget_crop": "^2.2",
    "drupal/crop": "^1.5",
    "drupal/advagg": "^3.5",
    "drupal/advagg_js_minify": "^3.5",
    "drupal/advagg_css_minify": "^3.5",
    "drupal/better_exposed_filters": "^3.0@alpha",
    "drupal/block_visibility_groups_admin": "^1.3",
    "drupal/chosen": "^2.6",
    "drupal/chosen_field": "^2.6",
    "drupal/content_export_csv": "^3.0@beta",
    "drupal/contentimport": "^4.1",
    "drupal/event": "1.x-dev",
    "drupal/entity_reference_views_select": "^1.3",
    "drupal/imce_search_plugin": "^1.0",
    "drupal/inline_entity_form": "^1.0@RC",
    "drupal/job": "^3.0@alpha",
    "drupal/media_bulk_upload": "^1.0@alpha",
    "drupal/memcache": "^2.0",
    "drupal/purge_ui": "^3.0@beta",
    "drupal/purge_processor_lateruntime": "^3.0@beta",
    "drupal/purge_tokens": "^3.0@beta",
    "drupal/twig_tweak": "^2.1",
    "drupal/views_bulk_operations": "^2.5",
    "drupal/block_visibility_groups": "^1.3",
    "drush/drush": "^9.5",
    "drupal/we_megamenu": "^1.5",
    "drupal/views_infinite_scroll": "^1.5",
    "drupal/embed": "^1.0",
    "drupal/dropzonejs": "^2.0@alpha",
    "drupal/purge": "^3.0@beta",
    "drupal/address": "^1.4",
    "drupal/acquia_connector": "^1.16",
    "drupal/purge_purger_http": "^1.0@beta",
    "drupal/smtp": "^1.0@beta",
    "drupal/content_sync": "^2.1",
    "drupal/console": "~1.0",
    "drupal/devel": "^2.0",
    "drupal/core": "8.6.13"
},

```

# Answer
> 1 votes
This looks like a composer issue. Sometimes composer isn't that great at handling complex dependencies. If you want to get rid of the error, many people have success going "nuclear":

1. Back up your site completely
2. Remove core folder, vendor folder and composer.lock - E.g. if you are on linux `$ sudo rm -rf docroot/core vendor composer.lock`
3. Run composer update `$ composer update`

---
Tags: 8, composer
---


# Question
Title: Same node to show using different themes
Drupal 8 question: I need to show same content page (say /node/12) using different themes, when used in a menu link. I have 'URLs aliases' created (eg: /ma/testPage, /nj/testPage ) both points to /node/12 (URL aliases module).

I have 'switch page theme' module which points to different themes based on the path (/ma/\* points to theme1, /nj/\* points to theme2).

When I view the page using /nj/testPage or /ma/testPage, it uses the same theme (theme1). As per the rule in 'Switch page theme' i am expecting the same node render using different theme. It doesn't happen like that. Could anyone help what i am doing wrong? Or is it not possible to render same node using different theme?

# Answer
The Switch Page Theme module not supported "switching by aliases" yet.

See details here Theme switching not working with aliased paths?
> 1 votes

# Answer
You can use the patch (https://www.drupal.org/project/switch\_page\_theme/issues/2929541) in Switch Page Theme module to show the same nodes with different themes.
> 0 votes

---
Tags: 8, theming
---


# Question
Title: How to display the views page title in a custom fieldable block
Goal: To create a custom fieldable block as available out of the box in D8, which also shows the page title of a a views page, if the page it is displayed on is a views page.

I created a custom block type, and added an image field for the block background.

I then copied and modified the block template to include:

```
{% if title %}
  <h1>{{ title }}</h1>
{% endif %}

```

But the views title does not show up. The page source shows nothing rendered. I enable theme debugging and the new block template is being used.

# Answer
Views sets the title configured in a Views page statically in the route definition. Get this title from the current route in a preprocess hook for your specific block content UUID. Add a `route`cache context, so that the block changes the title when you visit different pages:

```
function mytheme_preprocess_block(&$variables) {
  if ($variables['plugin_id'] == 'block_content:12345678-1234-5678-90ab-1234567890ab') {
    $variables['title'] = \Drupal::routeMatch()->getRouteObject()->getDefault('_title');
    $variables['#cache']['contexts'][] = 'route';
  }
}

```
> 1 votes

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


title: Control access to taxonomy terms

text:
# Question
Title: Control access to taxonomy terms
In my project I have companies, which are taxonomy terms, which can create invoices. Users and companies are a many-to-many relationship. I'm able to control access to the invoices using tac\_lite, but I've searched everywhere and can't find how to control access to the term page (/taxonomy/term/%). I want users to be able to see a list of their companies and a detailed page of each company, while denying access to other users' companies. Can I do that with tac\_lite? If not, how can I approach this? Sorry if this is not the right place to ask and if this is an obvious problem, I'm new to Drupal.

Thank you

# Answer
> 0 votes
You can try https://www.drupal.org/docs/8/modules/permissions-by-term, hope this can solve your problem.

---
Tags: taxonomy-terms
---


title: Remove left sidebar shopping cart

text:
# Question
Title: Remove left sidebar shopping cart
I know the shopping cart is generated by the view shopping cart form. But how do I remove the shopping cart block on left sidebar of the home page and still maintain the the view on /cart page? I have tried disabling the view entirely, that didn't work as it seems the block is hardcoded.

# Answer
> 1 votes
As far as I understand you could restrict block from being shown in front page, from block visibility settings. Alternatively, you could also make a custom template for the front page.

---
Tags: theming, commerce
---


title: Drupal Commerce Payment Module

text:
# Question
Title: Drupal Commerce Payment Module
I am creating a Drupal commerce Payment module and planning to sell it through codecanyon. Is there any licencing issues if I proceed with this?

# Answer
Any module you distribute must be licensed under the GPL 2.0 or later. You are free to put it up for sale so long as anyone who buys it enjoys the same rights of redistribution - that's just the nature of Drupal's license overall. Anyone who buys your module will be free to put it up on drupal.org and redistribute it at will.
> 1 votes

---
Tags: commerce, payment-gateways
---


# Question
Title: Send private message - Subject and message filled in
I'm using the module Privatemsg to give users the possibility to *send messages to other users on the website*.

What I would like to do is:

A button on the **detail page of node with type equal to Proposal**, and when a user clicks on it a, they redirect to the page `messages/new` where the *subject* and *message* is **already filled in**.

Now I just have a static button on the detail page that doesn't do anything. But how can I create the functionality that they redirect and 2 form parameters are already filled in?

# Answer
> 0 votes
One way to do this is to use the Prepopulate module. This solution is not specific to Privatemsg.

As the module page notes:

> For example, the following URL,
>
> http://www.example.com/node/add/blog?edit\[title\]=this is the title will automatically fill the Title field on a new blog post with the words "this is the title". Any field can be prepopulated this way, including taxonomy and CCK fields. You can prepopulate more than one field at a time as well.

# Answer
> 0 votes
Similar to the original posting requirements above, I required something similar, but used a Rules Link created Bootstrap Button situated on a Node page to which then redirected the Action Rule to the Message page and used the following syntax to autocomplete the Recipient field fill of both the message and the said Subject:

messages/new/?edit\[recipient\]=\[node:author\]&edit\[subject\]=\[node:title\]

The Prepopulate Module was utilised to provide the tokens as in \[recipient\] \[node:author\] etc.

Once implemented it was very easy and fires off very well to which the recipient gets the message and can then reply back.

---
Tags: 7, nodes, forms, users, privatemsg
---


# Question
Title: Trying to access and print the values from the fields within Paragraph
I'm having trouble trying to access and print the values manually within the Paragraph. This is a snippet from the paragraph field template I have created. I wanted to access and print values manually instead of Drupal generating the markup using `{{ slides.content }}` so that I could customize the markup myself

```
{% for slides in items %}
    {{ slides.content['#options'].entity.field_label.value }}
{% endfor %}

```

# Answer
> 2 votes
Here's what worked for me to manually get parts of a field in a paragraph template.

This is in a field template for the actual paragraph, so for me `field--field-paragraph.html.twig`. I have an image field with the machine name `field_image`. This prints just the alt text of that image.

```
{% for item in items %}
  {{ item.content['#paragraph'].field_image.0.alt }}
{% endfor %}

```

I looked here for working with paragraph templates: https://www.drupal.org/project/paragraphs/issues/2662766#comment-12528934 and here for general drupal 8 field-getting: https://blog.usejournal.com/getting-drupal-8-field-values-in-twig-22b80cb609bd

# Answer
> 1 votes
I'd recommend not to use field templates for things like this, but use an entity template (like `paragraph--BUNDLETYPE.html.twig`) instead.

In an entity template you can access the rendered HTML output of any sub-field like `{{ content.field_whatever }}`, but you can also access raw field values for stuff like `{% if paragraph.field_whatever.value == 'foo' %}`

---
Tags: theming, paragraphs
---


# Question
Title: How can I return a 404 error page in a node view?
How can I return a `404 error` page when a non-registered user tries to see a node page of a specific content type? And of course, the registered users can see the node page normally.

# Answer
Drupal permission system provides fine grained permission control for "create", "edit", "delete" actions for every node content type, but viewing action is covered by general "View published content" permission option that covers all content types.

In order to deny access to anonymous users when they are trying to view a node of certain content type, you need to include a function in a custom module that implements `hook_node_access()`:

```
/**
 * Implements hook_node_access().
 *
 * Disallow anonymous user to view nodes of type "EXAMPLE".
 */
function MYMODULE_node_access($node, $op, $account) {
  if (user_is_anonymous() && $op == 'view' && $node->type == 'EXAMPLE') {
    return NODE_ACCESS_DENY;
  }
}

```

You need to replace MYMODULE with the module name that contains this function and EXAMPLE with the name of the content type that you wish to deny access to.

**UPDATE**: The code above would in fact return 403 (Access Denied) page, I'm sorry for confusion. The following code will return 404 (Page Not Found) page (only when user is trying to access the node of content type "example" in "full" view mode (usually by accessing the node by URL "node/NID\]":

```
/**
 * Implements hook_node_view().
 *
 * Disallow anonymous user to view nodes of type "EXAMPLE".
 */
function MYMODULE_node_view($node, $view_mode, $langcode) {
  if (user_is_anonymous() && $view_mode == 'full' && $node->type == 'EXAMPLE') {
    drupal_not_found();
    drupal_exit();
  }
}

```
> 3 votes

# Answer
# Rabbit Hole

You can try using the rabbit\_hole module. It is available for:

* Drupal 7
* Drupal 8

Rabbit Hole is a module that adds the ability to control what should happen when an entity is being viewed at its own page.
> 1 votes

---
Tags: nodes, users
---


# Question
Title: How to change name of result of rest export?
I have a custom entity (ContractSubscription) created in a custom module (amap).
One of its fields (contract\_id) is a link to another custom entity (Contract) of the same module.

I created a View to export content of ContractSubscription as a csv file using REST Export.
Among the settings of the view, I have:

* Path: /amap/contract/export
* Contextual filters: 'Contract subscription : Contract' (this allows me to view only the subscriptions related to a specific contract)

When I go to mysite/amap/contract/export/2, I have the expected result that I can save locally:

As far as I understand, the name of the result is defined by the actual path when the view is executed, i.e. '2' which is the end of the path (in fact the value of the contextual filter).

I'd like to have something like 'Contract2.csv' instead of '2'.
How can I do that?

# Answer
Finally, I did that:
In `amap.routing.yml`, there is

```
amap.export_subscriptions:
  path: '/amap/contract/export/{contract}'
  defaults:
    _controller: '\Drupal\amap\Controller\ContractsController::export_subscriptions'

```

In `ContractsController.php`, there is

```
  public function export_subscriptions($contract)
  {
    amap_exportCSV('amap_contracts_subscriptions', 'rest_export_1', $contract); <-- some code to run the View with $contract as Contextual Filter
    $sFileName = 'Contract-'. $contract .'-export.csv';
    $sFileNameWithPath = 'sites/default/files/_private/contracts/' . $sFileName;
    $response = new BinaryFileResponse($sFileNameWithPath);
    $response->setContentDisposition(
      ResponseHeaderBag::DISPOSITION_ATTACHMENT,
      $sFileName
    );
    return $response;
  }

```

And it works as expected (for any browser including Safari).
> 1 votes

# Answer
The HTTP header `Content-Disposition` will suggest the filename the browser will save as. What's needed here is to make the REST export to add the HTTP header.

It turns out there's an existing issue for the CSV Serialization module. The current patch in the issue will take the last part of the URL after the slash and appends `.csv` to it (e.g. `2.csv` in your example). You could modify the patch to use whatever filename you want to use for your CSV export.
> 1 votes

---
Tags: views, 8
---


# Question
Title: How to programmatically get list of available image styles
I'm able to get a list of fields using

```
$fields = array_keys(\Drupal::entityManager()->getFieldDefinitions('node', 'ce_meeting'));

```

But is there a way to get a list of Image Styles instead? Something similar to

```
$fields = array_keys(\Drupal::entityManager()->getImageStyles());

```

to spit out an array

```
['thumbnail','original','medium','large','small']

```

Is there a function to display a list of available image styles?

# Answer
use

```
use Drupal\image\Entity\ImageStyle;

```

and load all image style with

```
$styles = ImageStyle::loadMultiple();

```

Also you can use entity\_load\_multiple with

```
 styles = \Drupal::entityTypeManager()->getStorage('image_style')->loadMultiple();

```
> 16 votes

# Answer
You can get a list of all image styles with an entity query:

```
$image_styles = \Drupal::entityQuery('image_style')
        ->execute();

```

If you query the config entity `image_style`, you get an array with a list of available image styles.

If you use `loadMultiple()` on the config entity, you get an array with the loaded config objects. Use this, if you need the configurations.

If you only need a list, use entity query, because this is faster.
> 6 votes

# Answer
If you'd like to get it with Drush on the CLI, use:

`drush ev "print_r(array_keys(\Drupal::entityTypeManager()->getStorage('image_style')->loadMultiple()));"`
> 1 votes

---
Tags: 8, media
---


# Question
Title: Create a zip file from a list of selected files and make the zipped file downloadable
I have a list of image files. I need to archive those files in zip format and make the archived file downloadable. I have seen `ArchiverZip` class defined in the `system module` of **Drupal 7**. But I couldn't be able to create a *zip* file. How can I do this in **Drupal 7** ? Is there any `hooks` or custom `modules` for this ? Please help me out with this.

**UPDATED** Following are the codes:

```
$zip = new ArchiverZip('archive.zip');
foreach($_POST['img'] as $fid):
    $query = db_select('file_managed', 'fn')
            ->condition('fid', $fid)
            ->fields('fn', array('filename'));
    $result = $query->execute();

    foreach($result as $row) {
        if(file_exists('sites/default/files/'.$row->filename)){
            var_dump($zip->add($base_path.'sites/default/files/'.$row->filename));
        }
    }
 endforeach;

```

And this reflects the following error

> *Exception*: Cannot open archive.zip in \*ArchiverZip-\>\__construct()\* (line *91* of *basepath\modules\system\system.archiver.inc*).

Please help me with this . .

# Answer
Make sure you include the class

```
module_load_include('inc', 'zip_archive', 'zip_archive.class');

```

Also check permissions for `archive.zip` file. Create one if its not there.
> 3 votes

# Answer
I don't believe the accepted answer is correct. You don't need to include the class. To get this to work, you need to make sure that the file you are passing the ZipArchiver constructor already exists - that is where I believe the original question was getting the error:

> Exception: Cannot open archive.zip

To make sure the file you are passing to the constructor already exists, try this (assuming the drupal path is something like a private or temp directory)

```
$filename = [drupal path] . [zip file name];
fopen(drupal_realpath($filename), 'w');
$zip = new ArchiverZip(drupal_realpath($filename));

```

We pass the path to `drupal_realpath()` so it converts the path from something like `"private://filename"` to `"[my app]/sites/default/files/private/filename"`.
> 1 votes

---
Tags: 7, files
---


# Question
Title: Get Absolute url using hook_preprocess_node
We are attempting to change the `$variables['url']` from a relative to absolute URL within the `mymodule_preprocess_node()` hook. The `$variables['url']` is displayed as a `<a>` element within our `node--page.html.twig` template.

**How can we set the `$variable['url']` so that it uses the `absolute` URL?**

`node--page.html.twig`

```
<a href="{{ url }}">
  {{ label }}
  {{ content.field_text }} {# custom text field #}
</a>

```

What we tried within `mymodule_preprocess_node()`.

```
use Drupal\Core\Url;

function mymodule_preprocess_node($variables) {
  $options = [
    'absolute' => true,
  ];
  $variables['url'] = URL::fromUri($variables['url'], $options);
}

```

This results in the following error message:

> The URI '' is invalid. You must use a valid URI scheme. in Drupal\Core\Url::fromUri() (line 281 of core\lib\Drupal\Core\Url.php).

# Answer
> 4 votes
In order to get this to work, I did the following. This assume you have access to the `$node` object, which you would if you are performing this within the `hook_preprocess_node()` hook.

```
$variables['url'] = $node->toUrl()->setAbsolute()->toString();

```

---
Tags: 8, theming, hooks, uri
---