title: Drupal 7 custom form date_popup element

text:
# Question
Title: Drupal 7 custom form date_popup element
Given this form

```
  $form['date'] = array(
  '#prefix'=>t('When do you want to start the featured campaign?'),
  '#date_format' => 'Y-m-d',
  '#date_year_range' => '0:+1',
  '#type' => 'date_popup',
  '#weight'=>0
  );

```

is there a way to display only future dates in the javascript popup ? I can't seem to figure it out. Thanks alot.

# Answer
Custom datepicker options are now supported (as of Date module version 7.x-2.6) by setting the necessary values with `#datepicker_options`. Alex's use case of a custom form element to display only future dates would look like this:

```
$form['date'] = array(
  '#prefix'=>t('When do you want to start the featured campaign?'),
  '#date_format' => 'Y-m-d',
  '#date_year_range' => '0:+1',
  '#type' => 'date_popup',
  '#weight'=>0,
  '#datepicker_options' => array('minDate' => 0),
);

```
> 6 votes

# Answer
Date use Jquery DatePicker: https://jqueryui.com/datepicker/#min-max

Then, We must do that from javascript:

```
  $(function () {
      $("#myIdinputDatePicker").datepicker({ minDate: -0, maxDate: "+1M +10D" });
  });

```

That's it, leaving the Drupal World.
> 1 votes

# Answer
As far as I know by default you do not have such option. The easiest way would be just to check it in validate function, and return an error if selected date is not from future.

On the other hand, a quick Google search returned for example this question - how to restrict the user to enter only today to future dates. using datepicker \- however you would need to test for yourself if it really works...
> 0 votes

---
Tags: datetime, forms
---


# Question
Title: Create a views "exposed filter" to compare two fields
First of all:

I know that there's a static filter with Global: Fields comparison that would do it. But I need an exposed filter in views to fullfill my needs.

Let's say I have a table with 3 cols: "nid" | "changed" | "another datetime".

Now I want to have an exposed filter as a select list with options "none", "old" and "new". If "old" is selected, show rows where "another datetime" \> "changed". If "new" is selected, show rows where "another datetime" \< "changed".

I've been looking for a solution for multiple hours.

# Answer
## Solution 1

Make use of views php to do the compare with the help of https://www.drupal.org/project/views\_php

In that case you have to write some code which is executed on each row, in the end it will work but it is very bad in maintaining. You do not have any integrated editor for error code checking etc etc. It is a solution but I do not recommend it.

## Solution 2

Make use of the hook views\_post\_execute with parameter of the view name.

function YOURMODULENAME\_views\_post\_execute(&$view){

For easy maintenance start with a switch

```
switch ($view->name){

    case "YOURVIEWNAMEA";
    case "YOURVIEWNAMEB";
    case "YOURCASEVIEW";

    foreach ($view->result as $row => $rowinfo) {

      // put here your code to do something with each result.

       // E.G Delete a value in the result of the view making use of unset statement
        unset ($view->result[$row]);

      }

```
> 1 votes

---
Tags: 7, views
---


# Question
Title: Are the data stored with the tempstore.private and tempstore.shared services expected to be removed when the user account is deleted?
Both the tempstore.private and tempstore.shared services store data which have an associated owner; for logged-in users, that is the user ID.

When an account is deleted, are the data having that user ID as owner removed?

I looked at `User::postDelete()`, but there isn't code for that.

```
public static function postDelete(EntityStorageInterface $storage, array $entities) {
  parent::postDelete($storage, $entities);
  $uids = array_keys($entities);
  \Drupal::service('user.data')
    ->delete(NULL, $uids);
}

```

It could be I didn't look at the correct class, or the code to delete those data is still missing from Drupal core.

Should I expect the data stored with the tempstore.private and tempstore.shared services be immediately deleted after a user account is deleted?

# Answer
> 1 votes
The user's temp storage deletion isn't attached to the user deletion process.

If you look at the class, `PrivateTempStoreFactory`, instantiated for `tempstore.private` & `tempstore.shared`, you can see that the class has an `expire` property that determines the storage's TTL (in seconds).

These services are instantiated with an `expire` value of defined by `parameters:tempstore.expire` in `core.services.yml`, with a default of 604800 seconds (1 week), so the temp storage will expire 1 week after its creation.

---
Tags: users
---


# Question
Title: mailsystem module does not appear in the selection field for HTML Mail module class
when I go to the `mailsystem` module configuration, only two selection fields appear

I do not know why this behavior can be given, there is some option that makes this disappear. I have installed the `mailsystem` and `htmlmail` modules

**What I see in the site where the selection field is missing**

**What should be shown (what I need)**

# Answer
Below where you show in your screenshot, see the "New Class" field set. Expand that

For the **Class to use for the format() (link is external) method** field select HTMLMailSystem

**Class to use for the mail() (link is external) method** select SmtpMailSystem

Save the form.

The new class will be available for use to set the Site Default.
> 0 votes

---
Tags: 7, emails
---


title: Testing upgrade to PHP 7

text:
# Question
Title: Testing upgrade to PHP 7
I have upgraded to PHP 7.1 on my local dev environment and my Drupal 7.59 site with CiviCRM 5.1.2 *seems* to be working just fine. I can't find any issues. I am wondering if there is a way in the CLI to check the compatibility of all enabled contrib modules or if I need to look each one up and/or just test extensively to see if anything isn't working.

# Answer
At this point assuming your site doesnt make use of extra modules, you can likely assume 7.x php works fine. I have found in numerous sites in the last few months that moving to php7 went fine and most php 7 were squashed in popular D7 modules in the last year or two.

If you have alot of custom modules you could try running a php 7 linter from github to check modules for php7 related issues, rather than trying to live-test drupal itself.

Something such as this github repo: https://github.com/wimg/PHPCompatibility
> 1 votes

---
Tags: 7
---


# Question
Title: Entity Reference widget selctor in view referring same reference
I searched for a solution but I didn't get it right. Given my setup:

1. A content type **Service**, referring a content type *Agency*
2. A content type **Agency**
3. A content type **Person**, referring a content type *Agency*

Now I need to add an entity reference in *Service* referring some of the *Persons*. The list of persons needs to be limited to the persons in the same Agency (of the service). I'm using an entity reference view to generate the list of the widget. I tried fetching the list of the person, using contextual filter(nid) and relationship but i didn't manage to make it right.

Therefore I'm asking for help. How should I setup the view?

Thank you all

# Answer
I couldn't test all the way with Entityref Views, I seem to have a bug in choosing Views on my Field settings. But I was able to create the Views and it works as expected in Views preview.

The goal is to create Views of sibling nodes. In your case we need to list Person nodes that are sibling nodes to the Service node you're currently viewing. They are sibling through the Agency Entity reference field (they both refer to the same Agency node).

## When both References to Agency are the same field

This is the case when the references to Agency from both Service and Person are **the same field, reused** (this happens when you create one ref field on one content type, then on the other content type you choose from the second drop-down "Re-use an existing field").

1. Create Content Views showing Person. You don't need Page nor Block, add Entity reference Display.
2. Show Fields Title and Agency (to test filtering works as expected, you can remove Agency later)
3. Under "Entity Reference inline fields" set Separator to `from` (with spaces on each side) so you get meaningful output Person: Name1 from Agency: Agency1
4. Add a Relationship **Content referenced from field\_agency**, you can require it. This is the Agency a Person listed in Views is referring to.
5. Add another Relationship **Content using field\_agency**, set it to **use the Relationship from the previous step**, you can require it. This is the reverse direction, pointing to all content that is pointing to this Agency.
6. Add a Contextual Filter **ID** from **Content** Category and set it to use the **second relationship** (field\_agency) and configure:
When the filter value is NOT available
**Provide default value**
**Content ID from URL**
When the filter value IS available or a default is provided
**Specify validation criteria**
**Service**
7. Configure Entity ref field settings to use this View, and choose the widget on "Manage form display".

That's it! You can test Views through Preview by entering one of the Service NIDs. Don't forget to add some "No results" text.

The Views will list only Person that are in Agency that this Service is referring to.

## When References to Agency are NOT the same field

This case is when you created two different Entity reference fields on Service and Person (they have different machine names). Configuration is a bit different even though they refer to the same Agency.

You create Views the same as above only with these differences:

1. The first Relationship needs to be of the Entity reference to Agency that is on the **Person** CT.
2. The second Relationship needs to be of the Entity reference to Agency that is on the **Service** CT.

Again this second Relationship must use the Relationship from the previous step. This is where the magic happens, where Service and Person Agency fields are compared.

The Contextual ID Filter needs to be using the second Relationship, as in the first case. This Contextual is only passing on the Service ID of the page you're on to Views.
> 1 votes

# Answer
After lot of tries, I gave up and use custom code, which took me 15 mins. That's how I did it:

```
function custom_dataset_views_pre_view ( &$view, &$display_id, &$args) {
  if ($display_id === 'entityreference_1') {
    // Get the node
    $url = arg();
    if ($url[1]) {
      $node = node_load($url[1]);
      $agency_id = $node->field_theme_working_group['und'][0]['target_id'];
      // Get the views filter
      $filters = $view->display_handler->get_option('filters');
      if ($filters['field_agency_target_id']) {
        // Change the filter
        $filters['field_agency_target_id']['value']['value'] = $agency_id;
        // Push the filter back
        $view->display_handler->override_option('filters', $filters);
      }
    }
  }
}

```

Less elegant, but finally working. Despite that, I still would like to know how to achieve this in plain views, or using tokens.
> 0 votes

---
Tags: entities, views
---


title: Pages are created for each image

text:
# Question
Title: Pages are created for each image
The Drupal 7.59 installation we have a new page for each uploaded image in the *files* directory. (It's been like this at least since Drupal 7.39 when I joined this project.)

If the image is *awesome-photo-by-Robin.jpg*, we will get *www.ourdomain.com/files/awesome-photo-by-robinjpg*. (The missing period before the extension is not a typo.)

The problem is that these pages get indexed by search engines, and because they have no content except header, image and footer, they get very low ranking and clutters our SEO results.

Obviously, these are automatically created during the upload process, where you have no possibility to disable or choose this. However, afterwards, one can go through /admin/content/file and edit the file and voilá, some information appears.

>

Removing the alias doesn't help, since the page remain anyway. (I also cleared the Drupal cache to make sure.)

1. Can these auto-generated pages be disabled somehow?
2. If they can't be disabled, we're considering adding `Disallow: /files/*` to the *robots.txt* file. Do you think that would work at all to amend this issue, or maybe cause other issues down the road?
3. What is the actual purpose of these pages?

This is the HTML that's surrounding the IMG tag, maybe it can give you any clues?

```
<div class="region region-content">
    <div id="block-system-main" class="block block-system">
        <div class="content">
            <div id="file-136" class="file file-image file-image-png">
                <div class="content">
                    <img typeof="foaf:Image" src="https://www.ourdomain.com/sites/default/files/fancy-image.png" width="425" height="282" alt="" />
            </div>
        </div>
    </div>
</div>

```

# Answer
> 2 votes
Don't think this is to do with core. Do you have the "File entity" module installed by any chance?

There's a permission of "View files" that anonymous users will have ticked in. If you untick that any of those /files/\* will get access denied for annon users

# Answer
> 0 votes
> What is the actual purpose of these pages?

This is not the default behavior of Drupal. So clearly a previous developer created this functionality for some reason. So backup your site before tinkering with it.

> Can these auto-generated pages be disabled somehow?

Yes, either it's being created via a custom module, or contrib module, or it's being created via Rules.

So you'll need to disable the module or rule (don't disable the rules module, but the actual rule listed in */admin/config/workflow/rules*)

Based on your screen shot, perhaps these pages belong to a content type. So once you disable the module or rule that is creating them, if you found no purpose for them, and want to get rid of them for good, you can delete the content type.

---
Tags: media, uri
---


# Question
Title: Form state redirects do not respect https
on some forms I added custom redirects, for example on the user login form:

```
function my_module_user_login_submit(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  $form_state->setRedirect('view.my_custom_view.page_1');
}

```

This is working well even with https on my test server: the user will be redirected after login to the view page with https, let's say https://my-domain.de/my-view-page

On another server the same is not working: on this server the domain is only reachable via https - not via http. This means calling http://my-domain.de will lead to a server error only using https://my-domain.de the project will be displayed. Now when I login I will be redirected to http://my-domain.de/my-view-page (without https) which leads to this server error.

I am sucessfully logged in: when I enter https://my-domain.de/my-view-page manually I can reach this know. When logout (I did not any changes here) the same appears: After logout the user gets redirected to http://my-domain.de.

Can somebody give me a hint what can be the problem on the second server?

Best, Tobias

# Answer
> 1 votes
> On another server the same is not working: on this server the domain is only reachable via https - not via http

Perhaps a redirect to force HTTPS was not set up on your other server.

see Enabling HTTP Secure (HTTPS). You can do this by altering the `VirtualHost definitions` on your 2nd server:

> ```
> <VirtualHost *:80>
>     ServerName www.example.com
>     Redirect "/" "https://www.example.com/"
> </VirtualHost>
>
> ```

or alternatively you can do it in the .htaccess file by adding:

> ```
> RewriteCond %{HTTPS} off
> RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
>
> ```

---
Tags: 8, redirection
---


# Question
Title: Filter a view by clicking on a link on another view
I have been searching all over the internet for a solution to my requirement with no success at all.

I am working on a Drupal 7 website using the latest version of views where i have one content type under the name of **Hotel Room** which contains the below fields:

* Title (= Room Nbr)
* Room images
* Room description
* Room Size
* Floor Nbr
* Bed Nbr

1) View name: View A

I have created a **block** view of format **fields** and displaying only the **content:title** of the content type **Hotel Room**

2) View name: View B

I have created another **block** view of format **table** and displaying all the fields available for the content type **Hotel Room**

3) I have placed both views on the homepage, where the View A is placed above View B.

4) What i need to accomplish is:

When i click on any **Title** inside the **View A**, **View B** will show me all the information related to the clicked **title**. And of course without the page being reloaded .

Here is an image describing what i need:

On the above image:

when i click on Room Nbr 18 inside View A, all the details about that Room Nbr will show up inside the below View (View B) without reloading of the page.

**Update:** The below image is what exactly i am trying to achieve in my drupal 7 website.

Is that possible to be done using Drupal 7 and views ?

Any help is much appreciated...

Thank you !

# Answer
There are several considerations in your question, using Ajax, filtering one view with another, displaying Exposed filter as a grid. Since you posted your desired goal I'll address it directly without much discussion about various issues raised.

To achieve this in D7 you need:

## Filtering one View with another View

1. Create Views of type Content showing Hotel room nodes.
2. Add Fields you want to be used in View A, as information for the filter
3. Add Entity reference Display to the Views and configure it to use at least one field (Title for example)
4. Save the View
5. Edit the View again and add Page display, configure the Path, and add the Fields you want in View B
6. Add a new Filter **Content: Nid (reference filter)**, expose it to visitors, and set the **View used to select the entities** to the Entity reference Views display we created in above steps. (It will be available as a choice if you saved the View after creating it.)

You should now have the Dropdown of your Hotel info from View A, and when you choose one choice from it, it will update the View B to show only that Room info.

Next we make it display in a list.

## Style it a little more closer to grid

1. Change `Exposed form style:` from Basic to **Better Exposed Filters** and configure it:
**Autosubmit**
**Hide submit button**
Under `Display "nid_entityreference_filter" (Filter label: "Nid (reference filter)") exposed filter as` select **Checkboxes/Radio buttons** or **Links**, whichever you like best or you think would be easier to style

Now you have a list of all your node titles, with additional information, and when you click on one, the results at the bottom will automatically update to show only that one room info.

You can use CSS in your theme to style it more like a grid from your screenshot.

If you don't want all the room results before a choice is clicked use the option **Require input before results are shown**.

---

Jump menu can be used as a method for filtering one view with another, but it won't be styled more easily to match your desired theme (it's a drop-down) so i won't document it here.
> 2 votes

---
Tags: 7, views
---


# Question
Title: Saving multiple field values in a users entity
I am trying to reference other nodes on the user entity on field\_clinic but everything else is saving except that multiple value field. What could i be doing wrong. The field\_clinic accepts multiple values. Below is my code:

```
$clinics = [

        array('value' => 132),
        array('value' => 133),
        array('value' => 134),
    ];

    // if the user exsists update basestation
    $UserEntity = User::create([
        'name' => 'Final',
        'roles' => array('subscriber'),
        'field_age' => '2',
        'field_city' => 12,
        'field_clinic' => $clinics,
        'field_base_statition' =>  $bs_nid

    ]);

    $UserEntity->save();

```

The clinics array contains the node ids that I am trying to reference. Please help

# Answer
> 5 votes
The way you're setting the values may be failing to work if you've got the wrong keys in your array - setting any field from code requires you to know how that specific field type stores its data in the entity.

If you're not sure about that key, using the devel module you can simply save one of those users filling the `field_clinic` field with appropriate values then switch to the `devel` tab for that user and inspect what keys are actually being used to store the values in that field (probably one named `target_id`).

According to what you find there, fixing your code may be just matter of changing this:

```
$clinics = [
    array('value' => 132),
    array('value' => 133),
    array('value' => 134),
];

```

to this:

```
$clinics = [
    ['target_id' => 132],
    ['target_id' => 133],
    ['target_id' => 134],
];

```

(disregard the difference between declaring an array using the `[]` or the `array()`, I used the former in my edited code just for coherency)

---
Tags: 8, nodes
---


# Question
Title: Webform field default value + Profile field value
I have a simple **Webform** (https://www.drupal.org/project/webform):

1. Single field called "name".

I also have a **Profile** (https://www.drupal.org/project/profile):

1. Profile is called "basic\_profile".
2. Profile contains 2 fields: "field\_name" and "field\_department".

I want the default value of my Webform field "name" to be the content of the user's Basic Profile value for "field\_name", but I cannot save the form because "*Default value* is using the following invalid tokens".

I have also tried using "\[webform-authenticated-user:display-name\]" which does not work.

I have tried using "\[current-user:display-name\]" which works but does not give me the info I want.

So how can I get the user's profile values to be used as default values for form fields? Thanks!

P.S.: The reason for this is that we are authenticating via Active Directory, and Drupal will be loading a user's profile from AD upon login. Therefore we want to leverage all data that exists in AD.

composer.json:

```
{
    "name": "drupal-composer/drupal-project",
    "description": "Project template for Drupal 8 projects with composer",
    "type": "project",
    "license": "GPL-2.0-or-later",
    "authors": [
        {
            "name": "",
            "role": ""
        }
    ],
    "repositories": [
        {
            "type": "composer",
            "url": "https://packages.drupal.org/8"
        }
    ],
    "require": {
        "composer/installers": "^1.2",
        "cweagans/composer-patches": "^1.6",
        "drupal-composer/drupal-scaffold": "^2.2",
        "drupal/adminimal_admin_toolbar": "^1.5",
        "drupal/adminimal_theme": "^1.3",
        "drupal/business": "^1.7",
        "drupal/business_responsive_theme": "^1.1",
        "drupal/console": "^1.0.2",
        "drupal/core": "~8.5",
        "drupal/devel": "^1.2",
        "drupal/domain": "^1.0@alpha",
        "drupal/domain_theme_switch": "^1.3",
        "drupal/eform": "1.x-dev",
        "drupal/honeypot": "^1.27",
        "drupal/insert": "^1.0",
        "drupal/maestro": "^2.1@RC",
        "drupal/mailsystem": "^4.1",
        "drupal/metatag": "^1.4",
        "drupal/module_filter": "^3.1",
        "drupal/paragraphs": "^1.2",
        "drupal/pathauto": "^1.1",
        "drupal/profile": "^1.0@RC",
        "drupal/token": "^1.3",
        "drupal/webform": "^5.0@RC",
        "drupal/workflow": "^1.0",
        "drush/drush": "^9.0.0",
        "kint-php/kint": "^2.2",
        "webflo/drupal-finder": "^1.0.0",
        "webmozart/path-util": "^2.3"
    },
    "require-dev": {
        "webflo/drupal-core-require-dev": "~8.5"
    },
    "conflict": {
        "drupal/drupal": "*"
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "config": {
        "sort-packages": true
    },
    "autoload": {
        "classmap": [
            "scripts/composer/ScriptHandler.php"
        ]
    },
    "scripts": {
        "drupal-scaffold": "DrupalComposer\\DrupalScaffold\\Plugin::scaffold",
        "pre-install-cmd": [
            "DrupalProject\\composer\\ScriptHandler::checkComposerVersion"
        ],
        "pre-update-cmd": [
            "DrupalProject\\composer\\ScriptHandler::checkComposerVersion"
        ],
        "post-install-cmd": [
            "DrupalProject\\composer\\ScriptHandler::createRequiredFiles"
        ],
        "post-update-cmd": [
            "DrupalProject\\composer\\ScriptHandler::createRequiredFiles"
        ]
    },
    "extra": {
        "installer-paths": {
            "web/core": ["type:drupal-core"],
            "web/libraries/{$name}": ["type:drupal-library"],
            "web/modules/contrib/{$name}": ["type:drupal-module"],
            "web/profiles/contrib/{$name}": ["type:drupal-profile"],
            "web/themes/contrib/{$name}": ["type:drupal-theme"],
            "drush/contrib/{$name}": ["type:drupal-drush"]
        },
        "patches": {
            "drupal/domain": {
                "Drupal Domain New Content Type Domain Fields": "https://www.drupal.org/files/issues/2018-03-15/2953168-da-form-display-13.patch"
            }
        }
    }
}

```

# Answer
According to Make profile fields avalaible as tokens, tokens for Profile fields was added, but it was added to **dev** 4 months ago. Since the 8.x-1.0-rc1 version was released 9 months ago, it does not have tokens.

So either switch to dev version until they release it or apply the patch provided on #22 to 8.x-1.0-rc1.
> 0 votes

---
Tags: 8, users, webforms
---


# Question
Title: How to skip step 1 on multi-step/wizard webform?
I need to skip step 1 and start on step 2 of a multi-step/wizard webform when a certain condition is true.

I found documentation regarding this, How to programmatically skip steps in wizard forms

The key part being in hook\_form\_alter putting

> ```
> $form_state->set('current_step', $all_keys[$goto_destination_step_index-1]);
>
> ```

What this does is fool drupal into thinking you're currently in the previous step that you want to go to, when in reality you're not. But the problem with this solution, is that it only works when you click the "next step" button and not on page load. Thus, the above solution only works for all but the first step.

I have tried doing

```
$form['progress']['#current_step'] = 'step_2';

```

But all this does change the progress marker to step 2, but I still see step 1's form.

I need to find a way to fool Drupal into thinking that I have completed step 1.

I tried doing `$form_state->set('form_field' $value);` when I looked at `form_state->getValues();` they were not set. I so I set them with `$form_state->getValues()['form_field'] = $value;` on all step 1 fields, but doing this alone does not trick Drupal.

There must be somewhere were Drupal stores that step 1 has been completed, but haven't been able to figure out where. My guess would be somewhere on `$form_state`, but I have not found it yet.

**Update:**

I don't really need the answer to this anymore, as the condition is no longer needed so it was decided to remove the question's step 1 altogether. But if you happen to know the answer, feel free.

# Answer
You can autosubmit step1 using JavaScript and it will direct user to step2. You can use Drupal behaviour so that no one can see step1.
> 1 votes

# Answer
You can use two submit functions- First submit will use for skipping without validating the current form step and second submit will use the validation and send the users to next step
> 0 votes

---
Tags: 8, webforms
---


title: Sub-sub Theme Not Inheriting CSS

text:
# Question
Title: Sub-sub Theme Not Inheriting CSS
I am trying to extend the Thunder Admin theme by creating a sub-theme in it. This is my first time making a sub-theme in Drupal 8 (other than from bootstrap starter kits).

I would have thought that a basic sub-theme would have inherited the css and js from its parent as is explained here

All I can see that I should need to do is to create a directory i.e. `my_theme` and create `my_theme.info.yml` and `my_theme.libraries.yml`.

The content of this file is as follows:

**my\_theme.info.yml**

```
name: My Theme
type: theme
core: 8.x
base theme: thunder_admin
description: 'Extends Thunder Admin'

libraries:
  - thunder_admin/global-styling

regions:
  header: 'Header'
  pre_content: 'Pre-content'
  highlighted: Highlighted
  content: Content
  page_top: 'Page top'
  page_bottom: 'Page bottom'
  sidebar_first: 'First sidebar'
regions_hidden:
  - sidebar_first

```

**my\_theme.libraries.yml**

```
global-styling:
  css:
    component:
      css/style.css: {}

```

Can any one please explain to me where I am going wrong please? I have flushed every cache I can think of

# Answer
> 0 votes
> Can any one please explain to me where I am going wrong please?
>
> ```
> libraries:
>   - thunder_admin/global-styling
>
> ```

There is no need to load the base theme's library, so this needs to be your theme's library.

```
libraries:
  - my_theme/global-styling

```

---
Tags: 8, theming
---


# Question
Title: Paste a full SVG content to CKEditor - not working
I tried to paste a full SVG content into the CKEditor Full HTML Source

But it gets corrupted and not working

# Answer
> 0 votes
You can solve this issue by disabling the content filters at

`http://<your website>/admin/config/content/ckeditor/edit/Full`

and choose `Advanced content filter` and select `disabled`

Warning: you should create a separate filter for ckeditor and allow only few trusted users to use Unfiltered Full HTML.

---
Tags: 7, wysiwyg
---


# Question
Title: Add/remove roles after submitting a certain webform
I know that we can achieve this via Rules but unfortunately, there are some known issues that prevent Rules in Drupal 8 to add a role properly.

So I was wondering if it would be possible to programmatically add and remove some roles to an authenticated user after submitting a webform.

For now, I'm simply trying to add a role called `styled` to the logged-in user, So I created a 'Webform Handler' called `webform_handler_role` and added that to the webform through UI, but I still can't get it to add the role using the following code (Also note that I have Ajax enabled for the webform):

```
<?php
namespace Drupal\webform_handler_role\Plugin\WebformHandler;

use Drupal\Core\Form\FormStateInterface;
use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\WebformSubmissionInterface;

/**
 * Webform submission action handler.
 *
 * @WebformHandler(
 *   id = "userrole",
 *   label = @Translation("User Role"),
 *   category = @Translation("User Role"),
 *   description = @Translation("Adds a user role after submission"),
 *   cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_UNLIMITED,
 *   results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
 *   submission = \Drupal\webform\Plugin\WebformHandlerInterface::SUBMISSION_OPTIONAL,
 * )
 */
class UserRoleHandler extends WebformHandlerBase {

  /**
   * {@inheritdoc}
   */
  public function postSave(WebformSubmissionInterface $webform_submission, $update = TRUE) {
    $user = \Drupal::currentUser();
    $user->addRole('styled');
    $user->save();
  }
}

```

And after the form submission I end up with the following error:

> "Error: Call to undefined method Drupal\Core\Session\AccountProxy::addRole() in Drupal\webform\_handler\_role\Plugin\WebformHandler\UserRoleHandler-\>postSave() (line 28 of /modules/custom/webform\_handler\_role/src/Plugin/WebformHandler/UserRoleHandler.php).")."

# Answer
> 2 votes
`\Drupal::currentUser()` loads only an Account, but you need a fully loaded entity to modify and save the user:

```
$account = \Drupal::currentUser();
$user = \Drupal\user\Entity\User::load($account->id());
$user->addRole('styled');
$user->save();

```

---
Tags: 8, rules, webforms
---


# Question
Title: Action links available options / caching
I have some action links defined in `module.links.actions.yml` which uses a custom "create entity" route. For entity creation I set up some restrictions and at some point the access is denied. The problem is that whilst the access to the page is denied, the action link is still visible until I clear all caches.

Is there a way to tell Drupal not to cache the links or to programmatically clear the links cache? Or some options I can add in the yml file to prevent caching?

Thanks.

# Answer
The following example implements an action link in Drupal 8 with the requirement of user-specific caching. This should allow you to hide/display the action link for the different users on your page. Providing different titles for different users should also work.

`mymodule.links.action.yml`:

```
entity.mymodule.add_form:
  class: Drupal\mymodule\Plugin\Menu\LocalAction\UserAction
  route_name: entity.mymodule.add_form
  title: 'Link to Add Form'
  appears_on:
    - entity.mymodule.collection

```

`mymodule/src/Plugin/Menu/LocalAction/UserAction.php`:

```
<?php

namespace Drupal\randomintro\Plugin\Menu\LocalAction;

use Drupal\Core\Menu\LocalActionDefault;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Routing\RouteProviderInterface;
use Drupal\Core\Routing\RouteMatchInterface;

/**
 * Defines a test local action plugin class.
 */
class UserAction extends LocalActionDefault {

  /**
   * The current user.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $currentUser;

  /**
   * {@inheritdoc}
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, RouteProviderInterface $route_provider, AccountInterface $current_user) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $route_provider);

    $this->currentUser = $current_user;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('router.route_provider'),
      $container->get('current_user')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheContexts() {
    return parent::getCacheContexts() + ['user'];
  }

  /**
   * {@inheritdoc}
   */
  public function getRouteParameters(RouteMatchInterface $route_match) {
    // If the user is not Anonymous.
    if (!$this->currentUser->isAnonymous()) {
      // Getting the uid.
      $uid = $this->currentUser->id();
      // Adding the link.
      return ['user' => $uid];
    }
    return [];
  }

}

```
> 0 votes

---
Tags: 8
---


# Question
Title: Restrict editing of content based on form value in content type
I'm not sure of the exact way to word this. I'm "just the designer". Where I'm working we've traditionally made a role per content type to limit access to editing/creating certain kinds of content. On a new (D8) site we're working on, we'd like to have a **single content type ("Room") and have different people be maintainers of those rooms depending on what's set in the "Building" field**.

The idea is to avoid having a ton of mostly-similar Room content types (that would all require updating when we want a change). And also of course to avoid people from other buildings editing rooms that don't belong to them.

(I think it'd be fine to have either 1) the rooms originally created by an admin and just have the building field hidden/disabled/limited when non-admins edit, or 2) even let them create new rooms with the building field limited based on their role/permissions.)

I don't know if there's a built-in way to do this, or perhaps modules you could recommend.

The developer I'm working with seems convinced that the only way to accomplish this is to build a custom form in PHP that essentially duplicates Drupal's built-in form for the Rooms content type we've made **(I'd really like to avoid this route, since it'd be a lot of hard-coded stuff that needs dev time, testing, maintenance, etc.)**. Thanks!

# Answer
> 1 votes
> (I think it'd be fine to have either 1) the rooms originally created by an admin and just have the building field hidden/disabled/limited when non-admins edit, or 2) even let them create new rooms with the building field limited based on their role/permissions.)

You could do this via a custom module or in your theme's **mytheme.theme**

```
function mytheme_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  // check form id for edit
  if($form_id == 'node_room_edit_form') {
    // Load the current loggedin user.
    $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
    // Check if user does not have administrator role
    if(!$user->hasRole('administrator')) {
      // get current node id
      $nid = \Drupal::routeMatch()->getParameter('node');
      // load the node
      \Drupal\node\Entity\Node::load($nid);
      // check if building field is not set to something
      if($node->field_building->value != 'something') {
        // remove access to field, make field not required so when
        // they save they don't get an error.
        $form['field_name']['widget']['#access'] = FALSE;
        $form['field_name']['widget']['#required'] = FALSE;
      }
    }
  }
  // check id for create
  if($form_id == 'node_room_form') {
    // logic goes here.
  }
}

```

---
Tags: 8, nodes, forms
---


# Question
Title: Ouput yes/no in commerce product table if product image available/not available
I am using Drupal 7 together with Drupal Commerce (not Kickstart). I am using a Bootstrap theme.

I have list of products displayed in a table that I created with Views. If you click on the Title, it goes to the product content page (display). Obviously, a product has an image if one is available. What I would want to do is to have a column in the table (Image), that would print out Yes or No, depending on if the image is uploaded (available) for the product.

Is this something that can be done in Drupal?

# Answer
Simply add your image field. When you add it, or if you click on it if you already added it, you will see something similar to the following date field screenshot.

* Click on rewrite results and put "Yes" here.
* Click on no results behavior and put "No" here.

---

> Is there a way to solve this in a similar way if you have a default image set - if none is uploaded a default image shows up?

In this scenario you would have to use Image URL Formatter and set the view image field formatter to display url.

Then you would simply perform a conditional check to see if the URL is equal to the default image url either using Views template file & custom code OR alternatively using Views Conditional for a zero coding solution.
> 2 votes

---
Tags: views, commerce
---


# Question
Title: Use a twig template instead of a render array in a custom module admin page
I have a Drupal 8 custom module, and I want to display its configuration page using the admin theme.

Usually, for this kind of pages I use, in the `_controller` property of my route, rather :

* a class that extends `\Drupal\Core\Form\ConfigFormBase` (for a simple form-like config page)
* a custom controller that extends `\Drupal\Core\Controller\ControllerBase` and returns a renderable array

For this module, I need to use complex HTML structure and a Javascript library for its configuration page. Writing all this directly in a `#markup` property of a render array would be too much work and highly not-maintainable.

Is it possible to write a custom template (twig or not), to render it programmatically and insert the result into a `container` element or in a `#markup` property ? And, as I use the Seven admin theme, I would like to do this without affecting the theme.

---

**\[Resolved\] Final solution :**

Combining leymannx answer and the elements mentioned below, I ended up with something that meet my requirements.

**mymodule.routing.xml**

```
mymodule.admin_ro:
  path: '/admin/config/mymodule/readonly'
  defaults:
    _controller: '\Drupal\mymodule\Controller\ReadOnlyController::index'
    _title: 'Module configuration - read only'
  requirements:
    _permission: 'view mymodule configuration'
  options:
    _admin_route: TRUE
    no_cache: TRUE

```

**ReadOnlyController.php**

```
class ReadOnlyController extends ControllerBase {

    public function index(){
        return array(
            '#type' => 'container',
            '#theme' => 'test-template',
            '#test_var' => [ 0, 1, 2, 3 ] // I needed an array type variable
        );
    }

}

```

**mymodule.module**

```
// Implements hook_theme()
function mymodule_theme( $existing, $type, $theme, $path ){
    return [
        'test-template' => [
            'render element' => 'container', // To render a simple container element
            'template' => 'test', // My template file name
            'variables' => [
                'test_var' => [] // Default value for my variable
            ]
        ]
    ];
}

```

And finally, my test template : **templates/test.html.twig**

```
<p>Hello !</p>
<!-- Just to see the content of my variable, after enabling twig debug mode -->
{{ dump(test_var) }}

```

---

**Related doc or posts**

# Answer
> 5 votes
The back-end theme automatically switches by path. So if your route's path begins with `/admin` it will show the page in the admin theme.

```
MYMODULE.MYPAGE:
  path: '/admin/config/MYPAGE'
  defaults:
    _form: '\Drupal\MYMODULE\Form\MYFORM'
    _title: 'MYTITLE'
  requirements:
    _permission: 'administer site configuration'

```

---

To render a form inside your own template you could simply register a new theme implementation inside `MYMODULE/MYMODULE.module`.

```
/**
 * Implements hook_theme().
 */
function MYMODULE_theme($existing, $type, $theme, $path) {

  return [
    'MYNAME' => [
      'render element' => 'form',
      'template'       => 'MYTEMPLATE',
    ],
  ];
}

```

And in the form you set this as the form's `#theme`.

```
$form['#theme'] = 'MYNAME';

```

And in the `MYMODULE/templates/MYTEMPLATE.html.tiwg` template you print it like so:

```
<div class="foo bar">
  {{ form }}
</div>

```

---

Any additional library also can simply be `#attached` directly to the form.

```
$form['#attached']['library'][] = 'MYMODULE/MYLIBRARY';

```

---

### Read More

\[drupal.org\] Create custom twig templates for custom module.

---
Tags: 8, theming
---


# Question
Title: How to change order and depth of user account tabs
With Tab Tamer we can change the weight/order of tabs in the user account under user/% (e.g. put user/%/edit after user/%/some\_settings), but we can't set depth between the tabs (e.g. user/%/some\_settings under user/%/edit/some\_settings).

With User Tabs we can create some depth at least for user/%/edit (makes it as a subtab of *Account*), but it doesn't offer options to put other tabs as subtabs of *Account*.

So how to transform tabs to subtabs in the user account?

# Answer
I forked User Tabs and added new subtabs (see NEW-SUBTAB in code):

```
/**
 * Implements hook_menu_alter().
 */
function usertabs_menu_alter(&$callbacks) {
  $callbacks['user/%user/account'] = array(
    'title' => 'Account',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
    'load arguments' => array('%map', '%index'),
  );
  //move the original edit and view items to below this container
  _usertabs_move_item($callbacks, 'user/%user/view', 'user/%user/account/view', MENU_DEFAULT_LOCAL_TASK);
  _usertabs_move_item($callbacks, 'user/%user/edit', 'user/%user/account/edit', MENU_LOCAL_TASK);
  _usertabs_move_item($callbacks, 'user/%user/NEW-SUBTAB', 'user/%user/account/NEW-SUBTAB', MENU_LOCAL_TASK);
  unset($callbacks['user/%user_category/edit/account']);
  if (($categories = _user_categories()) && (count($categories) > 1)) {
    foreach ($categories as $key => $category) {
      // 'account' is already handled by the MENU_DEFAULT_LOCAL_TASK.
      if ($category['name'] != 'account') {
        //it was too friggin complicated to support %user_category
        //see comments in user_category_load
        //all it does is check that the category name is valid
        _usertabs_move_item($callbacks, 'user/%user_category/edit/' . $category['name'], 'user/%user/account/'.$category['name']);
        $callbacks['user/%user/account/'.$category['name']]['tab_parent'] = 'user/%/account';
      }
    }
  }
}

```
> 0 votes

---
Tags: 7, users, navigation
---


# Question
Title: commerce product display showing only one product when multiples selected
I'm working on a Drupal 7 site using Commerce module.

When adding multiple products to a product display, I'm only seeing a single "Add to cart" button for the first product in the reference field, with no select menu for the additional products.

What's strange is that I *did* have that showing on the node, but not now - although I've only been changing view templates. Is there some config I should check to make sure this functionality is enabled that I may have inadvertently changed?

How would I ensure that a product display shows multiple products properly?

# Answer
Check the Display settings for the Product Display type in Structure -\> Content -\> Product Types, and make sure that the Product field is set to be visible on all view modes.

Set it to "Add to Cart form" and it will display a choice of all applicable products.

Note - I had a duplicate "product" reference field on products which confused the issue, and this was what was displaying the single "add to cart" button.
> 1 votes

---
Tags: 7, commerce
---


# Question
Title: Search and display node by scanning a barcode image
I am developing a new tracking system for my fashion store to have a good relationship with my returning back customers using drupal 7.

### THE SCENARIO:

**1)** When a customer come into my store and buy some products, he/she will be given a plastic card with a barcode on it, and ask him to present this card to the cashier every time he/she visits our store.

**2)** When the customer will come back later and present his/her card, the cashier will scan their plastic card using a barcode scanner device attached to the computer where the drupal website is always loaded in the browser.

**3)** Upon scanning of the plastic card, the website will perform a quick search based on the barcode input data and return two possible actions:

First Action:(If the card was not found on the system)

Information message: This card in not registered into the system.

Second Action: (If the card was found on the system)

Display a page contain information related to the scanned card like first name, last name, last purchased items, phone number....

### MY WAY OF APPROACH:

**1)** I created one content type VIP Customer and added to it the below fields:

Barcode field (using the barcode module) First Name Last Name Phone Number Last purchased items ....

**2)** Create a webform with one text field to scan the barcode . (Using webform or entityform module)

**3)** In order to not let the cutomers wait for the cashier to prepare the plastic card and printed out and...

All plastic cards will have to be prepared earlier and in order to do that i decided:

* Create around 500 nodes of type VIP customer where the field barcode is the only field which is filled by some data.
* The data filled inside each barcode field is a arbitrary mix of text and numbers just to create a barcode image for each node.
* Take all of the barcode images and give them to a library in order to print the barcode images on plastic cards.
* Now, I have around 500 plastic cards with barcodes printed on them and each related to a node on my drupal website and ready to be used directly.

**4)** When a customer will come, the cashier will take a new plastic card and scan it using a scanner reader and here the magic will happen:

* The cashier will open the webform and scan the barcode on the plastic card.
* The barcode scanner will input the code behind the barcode image into the text field.
* Automatically when this text field is filled up with some data, a quick search will take place and find the only node which related to the scanned barcode image.
* The node will be displayed to the cashier and here the cashier can edit the node to add information about the customer.
* When finish, the cashier will save the node and give the card to the customer.

**5)** When the customer will come back later, the cashier will take the card from the customer and scan it.

* The node should automatically open on the screen and the cashier can read all the information related to that customer.

### PROBLEMS:

* How to transfer the code from the barcode image to the text field on the webform upon scanning ?
* and what is the best approach for performing the search among all nodes and pull out/display only the node related to the card being scanned.

If the above is possible with drupal I prefer to use the drupal core and contributed modules without any written custom codes.

(I am good with drupal but not good in php coding)

Thank you for your time and support.

# Answer
> 0 votes
> How to transfer the code from the barcode image to the text field on the webform upon scanning?

AFAIK most of the scanners place value into focused form element (the one with the cursor in it). So make sure that field is focused when you load the page and that should cover your first question. You can probably use contrib modules (eg. https://www.drupal.org/project/focus) to achieve it without any custom Javascript.

> and what is the best approach for performing the search among all nodes and pull out/display only the node related to the card being scanned.

I think the easiest approach is to create a View with exposed filter (barcode). Then after scanning the barcode on the plastic card, you'll be one click away from a node for an existing card.

---
Tags: 7, webforms
---


# Question
Title: How do I manually configure the Link module?
I would like to be able to add the `file://` protocol to the list of `filter_protocols` so that we can add links to shared company files on a mapped drive from within our intranet website, but I'm not sure how to do this. Right now, it is apparently not included, according to Link Module Overview. Is there a way to manually configure this list in order to add `file://`?

# Answer
> 4 votes
You can override that in a container services file.

For example, create/edit /sites/default/services.yml, and add/alter the following lines:

```
parameters:
  filter_protocols:
    - http
    - https
    - ftp
    - news
    - nntp
    - tel
    - telnet
    - mailto
    - irc
    - ssh
    - sftp
    - webcal
    - rtsp
    - file

```

and make sure you have this line uncommented/added to settings.php:

```
$settings['container_yamls'][] = $app_root . '/' . $site_path . '/services.yml';

```

---
Tags: 8, files, uri
---


title: Override permissions per user

text:
# Question
Title: Override permissions per user
I have the following problem and I am currently looking for the best approach to solve it:

I have a site with various entities. These entities all have their own permissions to view, edit, delete and so on. Now I don't want to restrict the access to an entity per entity type but per entity element, with every user probably having access to different entity elements.

This means that I will need a very granular way to change permissions.

Thats why I would suggest to add a few basic roles to which you can assign your users. On top of these roles you are able to overwrite the permissions per user per entity element. This would probably happen in a seperate tab in the profile of a user.

If you have any idea on how to do so or you have another approach on my problem I would welcome your response.

Thanks in advance.

# Answer
I think you can use Access Control Lists. It does not have a UI on its own but your can use probably content access to give you the ACL functionality.

**NOTE:** After installing and configuring the ACL is not part of the user profile but part of the node (as you have suggested in your question)
> 0 votes

---
Tags: users
---


# Question
Title: views slideshow: display multiple items but scroll only one item at the time
i'm using drupal 8 and slideshow module to create a block of slides (fields with images and descriptions to it) to put it on some pages.

I have managed to show slides horizontally and they scroll nicely but problem is how to show 4 slides and scroll only by one at the time.

In setting for slideshow there is an option "Items per slide" if i use it and put 4 - i will get 4 slides on an block but it will scroll 4 items at time. If i put 1 - it will scroll one item at the time but will show only 1 slide and need 4.

plus to all that it should be responsive if only 3 slides can fit on the screen it should show 3 slides and scroll only one by one.

# Answer
I'd suggest using the owl carousel module from Git hub for responsive slide shows. It has lots of options to define how many slides based on breakpoints, support for mobile touch events, number of slides per next, and more.

We've been using it since 8.0 without a problem. Note that despite the Readme, the author has released it under GLPv2. See issue #4.

There is a cleaned up pull of this project as well. I have not used this but it may be a slightly better alternative.

Just install the module as a manual module or you can add the git hub repo as a repository in your composer.json and install it via composer. Once enabled, change your view format to Owl Carousel and then use the settings to define things.
> 1 votes

---
Tags: views
---


# Question
Title: Subtheme install settings in config but not showing
In a brand new site installation, I created a subtheme of the Bootstrap theme. In the subtheme (let's call "mytheme") config/install/mytheme.settings.yml file, I have the following settings.

```
settings:
  navbar_position: 'fixed-top'
  onelab_footer_type: Fat
  cdn_provider: custom
  cdn_custom_css: 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css'
  cdn_custom_css_min: 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css'
  cdn_custom_js: 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.js'
  cdn_custom_js_min: 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js'

```

I have verified that the database config table shows these settings. However, these settings are not getting applied. I have cleared the cache and that doesn't seem to do anything either. So, if they are correctly in the config table, how do I get Drupal to apply them?

# Answer
Although the documentation shows to place the settings under the "settings" key, I was then told to put it at the top level without the settings key. That is working.
> 0 votes

---
Tags: bootstrap-theme
---


# Question
Title: How to break up user roles checkboxes into groups?
When editing a user in Drupal 7 (/user/NID/edit), I'd like to break up the roles checkbox options. By default, it is just one list of roles. Instead, I would like to group different roles together to make it easier to read for the admins.

Ideally, there would be a group name header, followed by a certain subset of roles and then another head followed by another subset of roles, etc.

There is no change to the functionality of the roles. This is purely a theming exercise.

# Answer
> 2 votes
One way to do this would be to use some JS to add a header element in front of the role that starts the group. Each role has a unique id, e.g. `input#edit-roles-2`. You could use some jQuery like:

```
$("input#edit-roles-2").before("<h3>My Group</h3>");

```

You would have to order the roles the way you want and find the right ids.

Also, this will probably require using a custom admin theme or a module in order to inject the JS since user editing generally uses that theme and not the main theme.

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


title: Webform custom Options file location

text:
# Question
Title: Webform custom Options file location
My question is; When you create a custom option list in Webforms, where or how does the list get stored?

Explanation: In the Webforms Module (8.x-5.0-rc13) you have the ability to create custom options lists. The Options configuration page lists reusable predefined options/values available for select menus, radio buttons, checkboxes and Likert elements. (example: gender, sizes). The option lists that are included when the module is installed can be found as a yml files in docroot\>\>modules\>\>webform\>\>config\>\>install. After creating a custom option list I can not find the files anywhere or find a table in the database with the vales.

WHY? I have a list of 500 colleges that I want to populate a select list with different option values option text. pasting the list would be much easier and faster than using the interface to create the list.

I tried using a term select but cannot figure out how to define the value. I can only define the display text in the terms.

Sample yml code customized from one of the predefined option lists:

```
langcode: en
status: true
dependencies:
  enforced:
    module:
      - webform
id: my_colleges
label: US Colleges
category: Demographic
likert: false
options: |
  361623: ALASKA PACIFIC UNIVERSITY
  362001: ANCHORAGE COMMUNITY COLLEGE
  362503: UNIVERSITY ALASKA
  362814: SHELDON JACKSON COLLEGE
  363495: UNIVERSITY ALASKA

```

# Answer
> 1 votes
Webform options are config entities. You can export and import then via /admin/config/development/configuration.

You can also just bulk edit the options YAML. (/admin/structure/webform/config/options/manage/time\_zones/source)

Or you can use hook\_webform\_options\_alter() or hook\_webform\_options\_WEBFORM\_OPTIONS\_ID\_alter() to dynamic populate options from database or web service.

---
Tags: webforms
---


# Question
Title: Is it possible to synchronize publish status between translations?
Having 'Enable Translation' checked for a content type, is it possible to synchronize the publish status between all the translations in Drupal 8?

# Answer
You can't control the translation configuration of base fields such as the publish status field from the content type configuraton, so go to

> Administration \>\> Configuration \>\> Regional and language \>\> Content language

and uncheck the publish status field for your content type:

> \[ - \] Published

Now the publish option will be available only in the original language of the node and is then applied to all translations.
> 5 votes

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


# Question
Title: EFQ SQL error when using filedCondition on two different taxonomy terms
I'm using the below code to select a 'store' content type which has two taxonomy fields: category and brand.

```
$queryStore = new EntityFieldQuery();
$queryStore->entityCondition('entity_type', 'node')
  ->entityCondition('bundle','store', '=')
  ->propertyCondition('status', NODE_PUBLISHED)
  ->fieldCondition('field_city','tid', $city_id, '=')
  ->addMetaData('account', user_load(1))
  ->execute;

 if ($_GET['category'] != 'Choose a category'){
   $queryStore->fieldCondition('field_category','tid', $category_id, '=');
 }
 if ($_GET['brand'] != '') {
   $queryStore->fieldCondition('field_brand','tid', $brand_id, '=');
 }

```

However when I choose a brand like Chanel and a category like Food (naturally such node doesn't exist since Chanel doesn't do food), I get the following error:

PDOException: SQLSTATE\[42000\]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')) AND (field\_data\_field\_city0.deleted...

I'm using Drupal 7. Is there a way to avoid such error? I appreciate any help given

Thanks

# Answer
If you check your error you will notice that your query is trying to look for a column named field\_data\_field\_city0.deleted... , it appends a 0 to it. This problem occurs because the type of value you choose for that column in field query is not correct.

Can you check an confirm if field\_city is a taxonomy type of field. If you can access your DB check the table field\_data\_field\_city and check what is the name of last column.
> 0 votes

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


# Question
Title: How to disable the add to cart button if the shop owner does not have the premium role?
I created a marketplace (several stores on the same site) and the merchant can create a paid subscription to have the "Premium" role. Here's what I want to do:

* The owner of a store has the role "Premium" = the website visitors have access to the button "Add to cart" on the product pages of his store.
* The owner of a store does not have the role "Premium" = the website visitors do not have access to the button "Add to cart" on the product pages of his store.

How to disable the add to cart button (FOR VISITORS) if the owner of the store does not have the "Premium" role? *

Can I do that with a TWIG? If yes, how ?

Read my question. Depending on the role of the owner of a store, all users must be impacted.

WHY :

On my markerplace, I want to set up a paid subscription for sellers.

* If the owner of a shop is not subscribed, he can not sell his products ("Added to Cart" button disabled).
* If the owner of a shop is subscribed, he can sell his products (button "Added to cart" activated).

Whether the owner of a store is subscribed or not, everyone needs to see the stores and products. Only the "Add to Cart" button is impacted.

# Answer
Yes, you can do this in twig file. So you will have to create a commerce product twig file(you can copy it from commerce module template). In the preprocess hook you will have to pass a value whether that product can show cart button or not. In your twig file you can use value of that flag around {{ product.variation }}. Add to cart button is rendered by this variable.
> 0 votes

---
Tags: 8, theming, users, commerce
---


title: Pagination in a rest view api

text:
# Question
Title: Pagination in a rest view api
How to handle this situation in the Rest Export View as api.

We want to fetch a limit of 20 items in the api and with a load more feature. Currently our api produces hundreds of items.

In the Pager section, I can ofcourse select `Paged output, full pager` and specifiy `Items to display`, say 20. But how this works in the api? Since its only displaying 20 items, how does load more feature occur? Thanks!

This is my Pager settings.

```
PAGER
Items to display:Full | Paged, 20 items

```

# Answer
Simply pass the “page” parameter with the request, like ‘api/foo/bar?page=1’. Views will return the next set of results as you increment the page number. You can do the load more interaction however you want on the front end so long as you specify the page and keep track of total results.
> 5 votes

---
Tags: views, 8
---


# Question
Title: View won't render any content/teaser, only shows fields
I'm having a couple of articles which I want to display in a view. So I've set up a new view and made the following setting there:

```
Format: Unordered List | [default settings]
Show: Content | Full Content

```

All other settings remain untouched as default.

In the views-preview it is displayed nicely, but the whole view doesn't show up on the page when browsing to the path.

I've also tried

```
Show: Content | Teaser
Show: Rendered entity | Full Content

```

with no luck.

Only if I set the view to

```
Show: Fields

```

the view is displayed.

The article node pages are being displayed without a problem. I'm working with views for years now, and never had such a problem. Any ideas where the problem is?

Thanks, Marc

# Answer
check if this view did not get somehow to disabled list... go views list it's divided into Enabled and Disabled lists check there...
> 0 votes

---
Tags: views
---


# Question
Title: Where/how to install Drush when running multiple versions of Drupal
I use a Mac for Drupal development and am a long time user of Drush.

Getting ready to develop a new Drupal 8 site and installed via "Option A" as described https://www.drupal.org/docs/develop/using-composer/using-composer-to-manage-drupal-site-dependencies

Following those instructions "out of the box", I wind up with a Drush 9.x instance inside of the Drupal 8 repository.

It is my understanding that Drush 9 won't support Drupal 7. So, I'm forced to have multiple versions of Drush unless I run one global instance of Drush 8.x. At least so it seems to me.

I'm also trying to make the shift to composer and installed Drush 8 as documented here.

And sadly, that instance breaks unless I list the mysql host as "127.0.0.1" (instead of localhost). And if I do that, Drupal breaks.

So - first question: 1) What is are the recommendations for Drush installation on a Mac running multiple versions of Drupal. Is it preferred to run on global instance? (Drush 8.x) - or leverage composer to install Drush locally within each Drupal instance.

2) Why (maybe out of the scope of this discussion) do I suddenly get an error installing Drush 8 using composer on my Drupal 7 instance? Drupal 8 fails as well, but a different error.

# Answer
> 3 votes
You can run Drush 8 and Drush 9 at the same time.

## Drush 8

Install Drush 8 globally:

```
# Browse to https://github.com/drush-ops/drush/releases and download the drush.phar attached to the latest 8.x release.

# Test your install.
php drush.phar core-status

# Rename to `drush` instead of `php drush.phar`. Destination can be anywhere on $PATH.
chmod +x drush.phar
sudo mv drush.phar /usr/local/bin/drush

# Optional. Enrich the bash startup file with completion and aliases.
drush init

```

Reference http://docs.drush.org/en/8.x/install/

## Drush 9

Use a composer based Drupal 8 scaffold which contains Drush 9:

```
composer create-project drupal-composer/drupal-project:8.x-dev some-dir --stability dev --no-interaction

```

Reference https://www.drupal.org/docs/develop/using-composer/using-composer-to-manage-drupal-site-dependencies

## Running Drush

You don't need a launcher to run `drush`, because the global Drush 8 acts as one if it finds a locally installed Drush. So you can install a different Drush version for each Drupal site and have always Drush 8 as fallback globally. But I wouldn't recommend to install Drush 8 locally, in my experience the current Drush 8 works downloaded as phar file the most reliable. Ignore all older instructions how to install Drush by composer.

BTW if you still have a non composer based Drupal 8 site, the global Drush 8 works for Drupal versions \> 8.3 as well, despite that it's not officially listed in the compatibility list. And you need Drush 8 to manage a Drupal 8 site without composer, because in Drush 9 the tools to manage Drupal without composer have been removed.

---
Tags: drush
---


# Question
Title: Returning a custom command via AjaxResponse
I have a method that is invoked by AJAX call, and it returns an `AjaxResponse`. It redirects the user with `RedirectCommand`, added to the response. However, I would like to change it to a conditional redirect. Is this possible with `RedirectCommand`, or any other way that uses the `CommandInterface`, preferably in a way that does not require implementing `CommandInterface` in a new class?

# Answer
Indeed, one way to do this is to implement `CommandInterface` in a new class, as described in this blog post. This method adds the new command to `Druapl.AjaxCommands`.

However, if it's not desirable to implement the interface, a similar thing can be done with the existing `InvokeCommand` that implements `CommandInterface`, as seen in the example here.

My minimalistic example:

Server-side (`NULL` can be some CSS selector instead):

```
$response->addCommand(new InvokeCommand(NULL, 'customRedirect', ['/']));

```

Client-side:

```
jQuery.fn.customRedirect = function(target) {
    if (something)
        location.replace(target);
    else
        do_something_else();
};

```
> 2 votes

---
Tags: 8, ajax, redirection
---


# Question
Title: How to use different value from select options vs what's displayed? Name vs Realname
For adding multiple members to a group (course in opigno), I implemented the **chosen** module for better UX on the **select options** but instead of displaying usernames I want to display **realnames**.

Using **$account-realname** in the user loading loop displays them but after submission it breaks, as I think *it expects to receive name* instead.

> $form\['massadd'\]\['#options'\]\[$account-\>uid\] = $account-\>realname

```
$gid = current($form['group_ids']['#value']);
$node = node_load($gid);

$form['massadd'] = array(
'#type' => 'select',
'#title' => t('Select students to add to the group'),
'#required' => TRUE,
'#multiple' => TRUE,
);

$users = entity_load('user');
 foreach ($users as $uid => $account) {
  if ($uid && !in_array($uid, $exclude)) {
    $form['massadd']['#options'][$account->uid] = $account->name; // tried realname instead
  }
}

...

 $form['submit']['#weight'] = 0;
  // We validate our own way.
  unset($form['#validate']);
  $form['#submit'][] = 'opigno_simple_ui_form_og_massadd_massadd_form_add_roles';
  $form['#submit'][] = 'opigno_simple_ui_form_og_massadd_massadd_form_add_state';
  $form['#submit'] = array_merge(array('opigno_simple_ui_form_og_massadd_massadd_form_prepare'), $form['#submit']);

```

# Answer
Having changed it to **$account-\>name** I managed to find out what's going using devel command dpr($variable) which contained the users **uid**.

Then I just needed to replace the user lookup query accordingly to cross check from realname table with that of the users based on uid.

```
$query = db_select('realname','rn');
$query->join('users','usr','usr.uid=rn.uid');
$query->fields('rn', array('uid'));
$query->condition('rn.realname',$mail,'=');
$result =$query->execute()->fetchAll();

if (!empty($result)) {
$uids =array($result[0]->uid);
$account = user_load_multiple($uids);
$account = array_shift($account);
}

```
> 0 votes

---
Tags: forms, javascript
---


# Question
Title: Batch API times out when running a single operation
I'm trying to print ~100 nodes worth of content (Performance Plans) out to the private file system using the batch API. My process works perfectly up until about 10 of them and then times out. The timeout page happens before it even gets to the batch page with the progress bar. It appears to me like it might be running all 100 as a single batch vs breaking them up. I'm not sure exactly what I'm missing... Any help would be greatly appreciate.

BulkPrintForm.php

```
<?php
 namespace Drupal\bulk_print_to_files\Form;
 use Drupal\Core\Form\FormBase;
 use Drupal\Core\Form\FormStateInterface;
 use Drupal\node\Entity\Node;
 use Drupal\Core\Url;
/**
 * Class BulkAddForm.
 *
 * @package Drupal\create_perf_plan_for_new_year\Form
 */
class BulkPrintForm extends FormBase {
  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'bulk_print_form';
  }
  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['bulk_add'] = array(
      '#type' => 'submit',
      '#value' => $this->t('Print Performance Plans'),
    );
    return $form;
  }
  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $nids = \Drupal::entityQuery('node')
      ->condition('type','perf_plan')
      ->condition('field_performance_plan_year', 18)
      ->range(0, 100)
      ->sort('created' , 'DESC')
      //->condition('nid', 6273)
      ->execute();
    //$year = "1920"; //$year being left here as an example of passing a variable to the bulk process. Not currently in use.

    $operations = [];

    foreach ($nids as $nid) {
      $operations[] = [
        [
          $this->batchFunction($nid),
          [$nid]
        ],
      ];
    }

    $batch = array(
      'title' => t('Bulk Print happening within the Bulk Print Form file...'),
      'operations' => $operations,
      'progress_message' => t('Processed @current out of @total. Estimated time: @estimate.'),
      'init_message'=> t('Performance Plans are being printed to the private directory!'),
      'finished' => '\Drupal\bulk_print_to_files\BulkPrintNode::bulkPrintFinishedCallback',
      'error_message' => t('The migration process has encountered an error. (Make sure the folder you are placing these in exists!)'),
    );
    batch_set($batch);
  }
  function batchFunction($nid) {
    $print_engine = \Drupal::service('plugin.manager.entity_print.print_engine')->createSelectedInstance('pdf');
    $print_builder = \Drupal::service('entity_print.print_builder');
    $path = 'private';
    $filename = "perfplans/{$nid}.pdf";
    $nodes = \Drupal::entityTypeManager()->getStorage('node')->load($nid);
    $uri = $print_builder->savePrintable([$nodes], $print_engine, $path, $filename);
  }
}

```

BulkPrintNode.php

```
<?php
namespace Drupal\bulk_print_to_files;
use Drupal\node\Entity\Node;
use Drupal\Core\Url;

function bulkPrintFinishedCallback($success, $operations) {
    if ($success) {
      $message = 'Performance plan printed.';
      $type = 'status';
    }
    else {
      $message = t('Encountered an error during bulk performance plan creation.');
      $type = 'error';
    }
    drupal_set_message($message, $type);
  }
}

```

Is there a way to limit these to say doing 5 at a time and then moving on to another set? Im under the impression I just have the batching process setup incorrectly.

# Answer
In `BulkPrintForm::submitForm()` you invoke `batchFunction` method by calling it directly via `$this->batchFunction($nid)` line. This will effectively skip the batch API and run it for all nodes. You should pass the callback instead, check http://cgit.drupalcode.org/examples/tree/batch\_example/src/Form/BatchExampleForm.php#n93
> 1 votes

---
Tags: 8, batch-operations
---


# Question
Title: how to fix this Drupal\commerce\CommerceEntityViewsData' not found
installed Commerce reports using composer. On enabling the module got an error: "Fatal error: Class 'Drupal\commerce\CommerceEntityViewsData' not found". what is the solution for this i searched for CommerceEntityViewsData but i couldnot find what exactly it is please help me. i'm a newbie Thanks

# Answer
> 1 votes
Make sure you're using Drupal Commerce 8.x-2.6+ CommerceEntityViewsData was added in https://www.drupal.org/node/2882374

---
Tags: commerce
---


# Question
Title: Trigger redirect after Webform Remote Post Handler posted successfully
I've made a webform with a handler. This handler does a Remote Post towards an API. This API is actually a custom module within the Drupal install which (after some logic) passes all of the preprocessed data towards another API. When that is passed successfully I get a redirect URL back from them, but whatever I use (TrustedRedirectResponse or just normal RedirectResponse) it won't redirect. It just reloads the form.

How to solve this?

# Answer
I've added the following to the handler:

```
/**
* {@inheritdoc}
*/
public function confirmForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {
  if ($this->isDisabled()) {
    return;
  }

  $uri = new Url('entity.node.webform.user.submission', [
    'node' => $webform_submission->getSourceEntity()->id(),
    'webform_submission' => $webform_submission->id(),
  ]);
  $form_state->setResponse(new RedirectResponse($uri->toString()));
}

```

This seems to work.
> 0 votes

---
Tags: 8, webforms, redirection
---


# Question
Title: Check Content Type in Page PreProcess Hook
I'm attempting to get the content type in my page preprocess function...but apparently I'm missing something. What am I doing wrong here? I'm attempting to get the $node variables first - then test from there.

```
function mytheme_preprocess_page(&$variables) {
   $node = \Drupal::routeMatch()->getParameter('node');
   switch ($node->getType()) {
       case "client":
           $variables['attributes']['class'][] = 'clientpage';
       break;
        case "something_else":
           // ...
       break;
   }
 }

```

# Answer
> 4 votes
Instead of looking at the route parameter, you can also do:

`$node = $variables['node'];`

Here is some example code that I have that is working from `preprocess_page`:

```
    $node = $variables['node'];

    if ($node instanceof NodeInterface) {
      $type = $node->getType();

      if ($type == 'listing_page' && trim($node->getTitle()) == 'News') {
        $variables['is_news_page'] = TRUE;
      }
    }

```

Don't forget your `use ...` statement if you check node is `NodeInterface`.

So this is definitely doable - if you are getting any error messages please post them and double check your content type machine names.

---
Tags: 8, theming
---


# Question
Title: How to remove duplicate results from views block?
How to remove duplicate results from views block ? I have tried aggregation method and query distint but none of them working.

As previously i did the same by using the below code, but how to use the same code in drupal 8 ?

```
  function bootstrap_views_pre_render(&$view) {
      $used_nids = array();
       $new_view_result = array();

   if ($view->name == 'view_name') {
foreach ($view->result as $row) {
    if (!in_array($row->nid, $used_nids)) {
      $new_view_result[] = $row;
      $used_nids[] = $row->nid;
    }
}

$view->result = $new_view_result;
 }
  }

```

Is there any other possible solution of my problem ?

# Answer
> 7 votes
For anyone else looking for a Drupal 8 solution for Views Distinct, I was able to get this to work by creating a custom module with `MY_MODULE.views_execution.inc` file with this code:

```
<?php

use Drupal\views\ViewExecutable;

/**
 * Implements hook_views_pre_render().
 */
function MY_MODULE_views_pre_render(Drupal\views\ViewExecutable $view) {
  $unique_uuids = $new_view_result = [];
  $new_row_index = 0;

  // Loop through results and filter out duplicate results.
  foreach ($view->result as $row) {
    // Use UUID so this works for all entities
    $uuid = $row->_entity->uuid();

    if (!in_array($uuid, $unique_uuids)) {
      $row->index = $new_row_index;
      $new_view_result[] = $row;
      $unique_uuids[] = $uuid;
      $new_row_index++;
    }
  }

  // Replace $view->result with new array. Apparently views requires sequentially keyed
  // array of results instead of skipping keys (e.g. 0, 2, 4, etc), so we can't just
  // unset the duplicates.
  $view->result = $new_view_result;

  // Update the view index to match the new number of rows.
  $view->total_rows = $new_row_index;
}

```

---
Tags: 8
---


# Question
Title: Group Views results by split year (academic, fiscal, etc.)
I have several content types with Date fields. I would like to build a View that groups that content by our *academic* year, e.g. 2015-2016, 2016-2017, 2017-2018, etc.

I realize I would have to define those start and end dates somewhere (i.e. August 1 through July 31). It could be similar to a fiscal year as well.

I could do taxonomy terms, but I was hoping to not have to introduce another field if the date fields can accomplish this.

I am using Drupal 8.

# Answer
## Use Grouped Exposed Filter

Using a Grouped Exposed Filter for the `Authored on` field is the quickest and easiest way to filter out by academic year.

When you Expose a Filter, you can choose between `Single filter` and `Grouped filters`:

If you choose **Grouped filters** you can define your own items for the Exposed filter. In your case two academic years would be configured like this:

I haven't included time but you probably should to make sure that content created on July 31 and August 1 doesn't get exluded. Maybe something like `2017-08-01 00:00:00` and `2018-07-31 23:59:59` would work.

Add as many entries as you have academic years. Then when viewing your Views results choose the appropriate academic year option:

I've noticed grouped filters have some bugs in D8 when dealing with taxonomy terms, but I haven't noticed any problems with AuthoredOn field.

---

## Contextual Filter `Content: Created year + month`

If you include this Contextual Filter and choose to `Display a summary`:

you get links of months and years you click through to see content posted within those dates:

If that alone isn't enough maybe that can inspire you to create a similar custom Contextual filter with a bit more logic inside to do the same but for a configurable set of periods.
> 0 votes

---
Tags: views, datetime
---


title: How do I set up PHP configuration?

text:
# Question
Title: How do I set up PHP configuration?
I am running websites on my PC with following php5:

> /etc/php5/apache2/php.ini

(this is what I can see when running phpinfo() command within website php code).

How to set Drush, so it would use the same php version?

I found this page which says, that I should detect, where is my bin/php file in my PC and set it in DRUSH\_PHP environment variable. I have found following files:

> ./usr/bin/php
>
> ./usr/bin/php5

although, when I set this as DRUSH\_PHP variable (in ~/.bashrc file), my drush would stop work at all. Otherwise, without this setting of variable, I can run drush commands, that does not need PHP to run.

Can anybody help, how to proceed, to set the same php version for drush as it is used by website in phpinfo()?

# Answer
You can specify different PHP when running drush, e.g.

```
DRUSH_PHP=/path/to/php drush cr

```

In my configuration I've created the following symbolic (such as `php71` and `php72`):

```
/usr/local/bin/php71 -> /usr/local/opt/php71/bin/php
/usr/local/bin/php72 -> /usr/local/opt/php72/bin/php

```

in the local `bin/` folder which is in my `PATH`, so the commands are accessible.

Then I can run drush using different PHP version like:

```
DRUSH_PHP=php71 drush status

```

or:

```
DRUSH_PHP=php72 drush status

```

---

If you'd like to add `DRUSH_PHP` globally, add it to `~/.bashrc` or `~/.bash_profile` like:

```
export DRUSH_PHP=/full/path/to/php

```

Alternatively make sure your php path is in your `PATH` before any other versions.

To check whether you've multiple PHP version in your `PATH`, run this command:

```
which -a php

```
> 2 votes

# Answer
I spent half a day trying to re-install drush 8.x Finally stumbled on documentation for 7.x that fixed the 8.x problem.

Symptomatically, the PHP configuration came back blank. And as no surprise, DRUSH blew up when I attempted to run it within a Drupal instance.

```
 PHP configuration      :
 PHP OS                 :  Darwin
 Drush script           :  /usr/local/bin/drush
 Drush version          :  8.1.17
 Drush temp directory   :  /tmp
 Drush configuration    :
 Drush alias files      :

```

The answer was found HERE

I am running MAMP with PHP 7.2.1. So the PATH should be as shown below. That fixed the problem - finally!

```
export PATH=/Applications/MAMP/Library/bin:/Applications/MAMP/bin/php/php7.2.1/bin:$PATH

```
> 0 votes

---
Tags: drush
---


title: Why do I have conflicts in namespacing?

text:
# Question
Title: Why do I have conflicts in namespacing?
I'm building a traderbot for drupal and I have problems with the namespacing. Something is not working or I do not understand it correctly. I looked on several pages and questions but could not understand it.

The start

I runned all code without namespaces. Then it is working well !!!

I included a project called ccxt. In this project there are classes with the same name. They have a class called kraken and I have as well. There classes are in namespace ccxt.

So mine class should be namespaced. Which is very obvious.

As I do call from drush I need to have a own autoloader.

```
function autoloader_traderbot( $class_name ){

  // Because of namespaces $class_name could be string/string therefore only the last string should be taken
  if (($pos = strpos($class_name, '\\')) !== FALSE) {
    $class_name = substr($class_name, $pos+1);
    (new log)->add(4,'Class name adjusted. Namespace removed from class path.');

  }

  (new log)->add(4,'Searching for loading class  name  : ' . $class_name );

  $dir_iterator = new RecursiveDirectoryIterator(CLASS_DIR);
  $iterator = new RecursiveIteratorIterator($dir_iterator, RecursiveIteratorIterator::SELF_FIRST);

  foreach ($iterator as $file) {
    if($file->getFilename() == $class_name . ".class.php"){
      (new log)->add(4,'Loading class file name (.class.php) : ' . $class_name . ' in filename ' . $file );
      require_once tb_adjustfilename($file);
    }

    if($file->getFilename() == $class_name . ".php"){
      (new log)->add(4,'Loading class file name (.php): ' . $class_name . ' in filename ' . $file);
      require_once tb_adjustfilename($file);
    };
  }

}

```

So I add in kraken.class.php

```
namespace traderbot;

```

Then calling this object is working fine.

But then the problems are there

I also get

Error: Class 'traderbot\log' not found in traderbot\kraken-\>update\_ohlc() (line 48 of C:\www\tb\modules\custom\tb\src\exchanges\kraken.class.php) #0 \[31;40m\[1m\[error\]\[0m

I checked log.class.php.

This is not namespaced so I add

```
namespace traderbot;

```

But then I get from php

```
Error: Class 'traderbot\SplFileInfo' not found in traderbot\log->add() (line 66 of C:\www\tb\modules\custom\tb\src\library\log.class.php).
Drush command terminated abnormally due to an unrecoverable error.

```

But now I'm lost. Because this is just a normal php object so why is it going wrong?

## Addition

Thxs, with the help of the answers it is working now. I saw the excellent video, change the statements, disable my own autoloading procedure.

As a result of this I should add in my classes the use statement for every object I use. The only thing I find a little bit strange is the following.

In every php file with a class I should add the use statement for every object.

Example 1.

```
// Define namespaces and objects
namespace Drupal\tb\library;
use SplFileInfo;
class log{
}

```

Example 2

```
namespace Drupal\tb;

use Drupal\tb\library\log;
use Drupal\tb\datacollector\datacollector;
use Drupal\tb\datacalculator\datacalculator;
use Drupal\tb\scenario\scenario;

class traderbot{

    public function start(){

        (new log)->add(0,"Start data collector");
        $collector = new datacollector;
        ...

        (new log)->add(0,"Start data calculator");
        $indicators = new datacalculator;
        ...

        (new log)->add(0,"Start scenario handler");
        $sc_handler = new scenario;
        ...

    }

}

```

I red some other documentation and QA and understand dat wild card loading of namespacing is not possible. https://stackoverflow.com/questions/29851099/how-to-load-all-classes-of-a-namespace but I also red somewhere that as long as the class is in the same namespace it is not needed to put the use statement for this object. So then I come to the following questions for verification:

Q1) Adding a standard use statement for SPL looks very strange for me. Is this correct?

Q2) Adding a long list of several use statements from unique objects in the same namespace is very strange for me as well. Is this correct?

# Answer
> 3 votes
> This is not namespaced so I add
>
> ```
> namespace traderbot;
>
> ```

Clearly you don't understand the concept of namespaces, so I suggest you watch this short video.

After watching the video, you should come to the realization that you're telling PHP to open the "traderbot" folder which does not exist.

According the official Drupal docs on Namespaces, you need to structure it like this for Drupal:

> ```
> namespace Drupal\<module name>\SubFolder1\SubFolder2;
>
> ```

**Note:** Since Drupal uses autodiscovery the `\modules\custom` nor `\src` paths are not need to be declared here, since Drupal will automatically look inside of these.

**Note2:** the file name matters, needs to be YourClassName.php (case sensitive).

> Class Drupal\example\_module\Foo\Bar in namespace Drupal\example\_module\Foo should be in a file named example\_module/src/Foo/Bar.php

so you should remove the `.class` part from your file names. In Drupal the convention is to create a file for each class.

In /modules/custom/tb/src/library/**log.php** you need to put:

```
namespace Drupal\tb\library;

```

Then on /modules/custom/tb/src/exchanges/**kraken.php** to load a class that is in a different name space, you need to put at the top

```
use <name_space>\<class_name>;

```

so it would be:

```
use Drupal\tb\library\log;

```

---
Tags: 8
---


# Question
Title: Custom module over ride blazy.html.twig template
I have a small custom module that needs override blazy.html.twig that comes from the Blazy contributed module in Drupal 8. The code below shows what I have so far, can anyone give me some direction on how to go about this?

```
/**
 * Implements hook_theme().
 */

function slider_overlay_text_theme($existing, $type, $theme, $path)
{
    // In the template file I have blazy.html.twig
    $templates = $path . '/templates';

    return [
            'template' => 'blazy',
            'path' => $templates
    ];
}

/**
 * Prepares variables for blazy.html.twig templates.
 * Implements hook_preprocess_HOOK() for field templates.
 */
function slider_overlay_text_preprocess_blazy(&$variables) {

    // This variable is in the template ready to be printed
     $variables['display_hero_text'] = 'right-hero-text1';
  }

```

# Answer
> 1 votes
I found the issue to override the module template you have to call the modules name in the \_theme hook `$return['blazy']`.

```
function slider_overlay_text_theme($existing, $type, $theme, $path)
{
    $templates = $path . '/templates';

    $return['blazy'] = [
        'template' => 'blazy',
        'path' => $templates
    ];
    return $return;
}

```

---
Tags: 8, theming
---


# Question
Title: How to print/render nested Paragraph values to twig template?
I'm trying to figure out how I can render values from nested `Paragraphs`. Basically I have field/values from a `Paragraph` within a `Paragraph` I have tried experimenting and searching for answers but I can't seem display the values from the nested `Paragraphs` to the twig template.

Here is the sample of the code below that I have been working on

```
First Paragraph
{% for paragraph in node.field_sidebar_area %}

    <h2>{{ paragraph.entity.field_label.value }}</h2>

    <ul>

        {% for block_query in paragraph.entity.field_block_query  %}

            {{ block_query.entity.body.value | raw }}

        {% endfor %}

    </ul>

    <ul>
         {% for link in paragraph.entity.field_link_item %}

         <li>{{ link.url }}</li>
         <li>{{ link.title }}</li>

         {% endfor %}
    </ul>

    Second Paragraph
    {% for object in paragraph.node.field_sidebar_content %}

        {{ object.entity.field_label.value }}

    {% endfor }

{% endfor %}

```

# Answer
I am also curious about the best way to do this. While I'm still trying to figure out what that is, here is what I've done:

I've enabled the Twig Tweak module, and inside the first paragraph template, I pull in the second paragraph with a selected view mode.

```
{{ drupal_entity('paragraph', content.field_sidebar_area[0]['#paragraph'].id(), 'MY_CUSTOM_VIEW_MODE') }}

```

And then in the template for the second paragraph, I can adjust the Twig as I please. Note that the naming convention would be:

```
paragraph--PARAGRAPH-TYPE--MY-CUSTOM-VIEW-MODE.html.twig.

```

Best of luck!
> 4 votes

---
Tags: theming, entities, paragraphs
---


title: Create node before page load

text:
# Question
Title: Create node before page load
I have a web service on third party system that return property of doctor and I have a content type named "doctor". I want when user go to a url like doctor/23 drupal create a node of type doctor based on url arg and show this node to user. for that and with @zaporylie help i create a custom controller like bellow

create a Routing:

```
    showdoctor.load_doctor_controller_load:
  path: 'doctor/{doctor_id}'
  defaults:
    _controller: '\Drupal\showdoctor\Controller\LoadDoctorController::load'
    _title: 'load'
  requirements:
    _permission: 'access content'

```

and my controller like this:

```
    class LoadDoctorController extends ControllerBase
{
    public function load($doctor_id)
    {
        $result = RestCurl::post("http://myrest_server.com", [
            'filter' => ['doctor.id' => $doctor_id],
        ]);

        $fullname = $result['data']->message->data[0]->firstName;
        $fullname = $fullname . ' ' . $result['data']->message->data[0]->lastName;
        // Fetch doctor node with EFQ
        $query = \Drupal::entityQuery('node');
        $query->condition('type', 'doctor');
        $query->condition('field_doctor_id', $doctor_id);
        $nids = $query->execute();
        if (!$nids) {
            $node = Node::create([
                'type' => 'doctor',
                'title' => $fullname,
                'uid' => 1,
            ]);
            $node->set('field_doctor_id', $doctor_id);
            $node->save();
            $element = array(
                '#markup' => $node,
            );
            return $element;
        } else {
            $element = array(
                '#markup' => $node,
            );
            return $element;
        }
    }

}

```

Now for example when in go to doctor/23 page i see a page with load title. and if i refresh this page i see doctor page correctly. i think my problem is return value.

# Answer
> 2 votes
You should create a custom Controller rather than hook on page load. This way you won't have an overhead on every page load. In the Controller (accessible under `movie/{movie_id}` route) try to load movie by movie\_id (entityQuery), and if it does not exists simply create one based on data from 3rd party service and display in a display mode of your choice.

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


# Question
Title: How to get the values from a formatted field in inc file
I have a description field with a CK editor enabled. And when I get the data from it as `node->get('fieldname')->getString()` it outputs the content as below.

> The contents that I have entered in the Ck editor
>
> , basic\_html

I can resolve this in the twig file by getting this as `{{fieldname| raw}}`. But I need to get this in a php file. How do I get the value without that **, basic html** part?

# Answer
> How do I get the value without that , basic html part?

`$node->field_name->value;` should do the trick.

---

> I can resolve this in the twig file by getting this as `{{fieldname|raw}}`.

Using `| raw` filter in twig is bad security practice, see How do I get the raw field value in a twig template? for a safe solution.
> 3 votes

---
Tags: 8, nodes
---


# Question
Title: How can I set the default value for a Media form element?
I am using Media 2.0 and a media field in a custom admin form.

I am trying to set the default value as described on https://www.drupal.org/project/media/issues/1158760#comment-12656764, but \`#default\_value = array('fid' =\> 1234); doesn't work.

How can I set the default value for a Media form element?

# Answer
After some digging in the media module, this is the working notation:

```
'#default_value' => 12345,

```

Plain and simple...
> 1 votes

---
Tags: 7, forms, media
---


# Question
Title: How to use $config->get for #default_value when multidimensional
I am creating a form and I want to store the form values every time the form is saved, so I am using:

```
'#default_value' => $config->get('field_name')

```

However what would I do if my form item rather than being

```
$form['field_name'] = [
  '#type' => 'datetime',
  '#default_value' => $config->get('field_name'),
  '#date_date_element' => 'none',
  '#date_time_element' => 'time',
  '#date_time_format' => 'H:i',
];

```

was this

```
$form['section']['field_name'] = [
  '#type' => 'datetime',
  '#default_value' => $config->get('field_name'),
  '#date_date_element' => 'none',
  '#date_time_element' => 'time',
  '#date_time_format' => 'H:i',
];

```

I have tried unsuccessfully

```
'#default_value' => $config->get('section.field_name')

```

# Answer
> I have tried unsuccessfully
>
> ```
> '#default_value' => $config->get('section.field_name')
>
> ```

Probably because you didn't set it first with `section.field_name` otherwise you can't retrieve it if you have not set it with that name.

---

Field names are supposed to be unique, so nothing different.

It really depends on what you do in **set**, you could give it whatever name you like

`$config->set('lalalala', $form_state->getValue('field_name'));`

and then retrive it with `$config->get('lalalala'),`

but convention is to give it the field name:

```
$config->set('field_name', $form_state->getValue('field_name'));

```
> 1 votes

---
Tags: 8, forms
---