# Question
Title: Why are overrides not included in download file?
I have the problem, that some of my features are overridden and will not be updated after recreation.

For example there is one feature that needs a new dependency and the title of one view was changed. I want to include these changes in my feature and click on recreate. When i look into the download files, you can see, that the changes (dependency and view titles) are not included.

If i change the files manually, the feature has the status "Standard".

The feature includes content types, panel pages, fields, views, permissions and some strongarm variables.

Does anybody know, why my changes are not included, when recreating my features?

* Drupal v. 7.43
* Features v. 7.x-2.10

Thanks for your help.

# Answer
The solution was to use drush.

```
drush fu feature_name

```

After that all files were inclduded.
> 0 votes

---
Tags: 7, features
---


# Question
Title: Can I use drupal_get_form and drupal_render within a custom Drupal 7 input filter?
As the title says: I've got a custom input filter in Drupal 7 which replaces a token with a custom drupal form. Without showing the complete code, which might just confuse things, The main essence is the following:

```
function _my_filter($text, $filter = NULL, $format = NULL, $langcode = NULL, $cache = NULL, $cache_id = NULL) {
  $rendered_text = $text;
  preg_match_all(MY_CUSTOM_REGEX, $text, $matches);
  if (!empty($matches[0])) {
    foreach ($matches[0] as $match) {
      $custom_form = drupal_get_form('my_custom_form');
      $replacement = drupal_render($custom_form);
      $rendered_text = str_replace($match, $replacement, $rendered_text);
    }
  }
  return $rendered_text;
}

```

For some reason when the node is being saved this times out. I've narrowed it down to being something in my drupal\_get\_form (but this form renders fine without any problems outside of an input filter).

Can I use drupal\_get\_form and drupal\_render within an input filter like this?

# Answer
> 1 votes
I believe you can do this, but not by default. You'll need to disable caching. This is because the filtered data is cached, so your form will only work the first time. To disable caching, you need to set cache to FALSE in your hook\_filter\_info() definition.

If it's timing out, then it may be a problem in your form definition itself - does the for work in non-filter context (ie embedded directly into a page)?

---
Tags: forms, input-formats
---


# Question
Title: Remove Parent Theme Settings From Child Theme
I'm in the middle of creating a custom theme using the `Bootstrap` theme as it's parent. As you may, or may not be aware, the `Bootstrap` theme comes with lots of useful theme settings. These are great, but as this custom theme will be used for a client, most of these settings could be dangerous for them to be able to change.

I'd like to remove all of these theme settings, so only the ones I add in my custom theme will appear.

I know these theme settings would still be available to change in the `Bootstrap` theme, but that's not a problem.

Thanks

# Answer
This definitely isn't the nicest solution, but it does work. If you find a better one, do post it here.

```
function THEMENAME_form_system_theme_settings_alter(&$form, \Drupal\Core\Form\FormStateInterface &$form_state, $form_id = NULL) {
  unset($form['global']);
  unset($form['bootstrap']);
  unset($form['general']);
  unset($form['theme_settings']);
  unset($form['logo']);
  unset($form['favicon']);
  unset($form['components']);
  unset($form['update']);
  unset($form['javascript']);
  unset($form['advanced']);
}

```
> 1 votes

---
Tags: 8
---


# Question
Title: Best practice: Twig template for custom module's block
I'm looking to provide a template for a custom block in my custom module. There are two ways to go about this: provide a template for just the block's content, or provide a template that extends *block.html.twig*. I've returned empty-handed in my search for a best practice. Let me clarify the two options to provide a template for my custom module's block:

## Option 1: provide a template for the block's content

```
<?php
/**
 * Implements hook_theme().
 */
function mymodule_theme($existing, $type, $theme, $path) {
  return array(
    'mymodule' => array(
      'variables' => array('var' => 'test'),
    ),
  );
}
?>

```

The template named *mymodule.html.twig* looks like this:

```
This is my content: {{ var }}

```

## Option 2: extend block.html.twig

```
<?php
/**
 * Implements hook_theme().
 */
function mymodule_theme($existing, $type, $theme, $path) {
  return array(
    'block__mymodule' => array(
      'base hook' => 'block',
      'variables' => array('var' => 'test'),
    ),
  );
}
?>

```

The template named *block--mymodule.html.twig* looks like this:

```
{% extends "block.html.twig" %}
{% block content %}
This is my content: {{ var }}
{% endblock %}

```

## Looking for a best practice

The documentation on Twig Template naming conventions is quite clear on this: for a block, the name should be *block--module.html.twig*. However, is that the filename a themer would use to overwrite my block content (option 1) or is it the filename I should use for the template I provide for my custom module (option 2)? I haven't found a clear answer on this so as far as I can see there's no best practice on this yet.

# Answer
I would prefer option 1. Theme the inside of a block in a custom template with custom variables or build a render array with render elements. Use the block template only to theme the outside of the block, for example add a wrapper div.

Option 2 is not a good idea, because it uses this block template:

```
{% extends "block.html.twig" %}
{% block content %}
This is my content: {{ var }}
{% endblock %}

```

Normally a block template looks like this:

```
{% extends "block.html.twig" %}
{% block content %}
This is my content: {{ content }}
{% endblock %}

```

By ignoring {{ content }} in a block template no cache metadata can bubble up. See https://www.previousnext.com.au/blog/ensuring-drupal-8-block-cache-tags-bubble-page

You could try to add the cache metadata with block methods. But this is not good practice, because if later someone tries to add block content and is not aware of that the block template doesn't use the base hook variables this person will have a hard time debugging this.
> 3 votes

# Answer
I would prefer to use option 2, but depending on the use case without the {% extends... %} part and possibly at some template suggestions just in case that block is used in various contexts where the additional HTML is needed.
> 2 votes

---
Tags: theming, 8
---


# Question
Title: How to filter on taxonomy term in a view?
I've got a view where I would like to filter content based on a taxonomy term. I've created the taxonomy, added some terms, created a field reference on the specific content type I'd like to show, then added some terms to content.

The issue I have is this: In the view, under add new filter, the taxonomy I created doesn't show up as an option to filter by. There's a bunch of "indexed node: xxx" available, but none of them refers to the taxonomy I created. I suppose there is an option somewhere to have the taxonomy terms indexed? How do I do this?

This might seem like a very straightforward question, but for some reason on this particular website, I can't find the culprit.

# Answer
You need to create a relationship to your taxonomy vocabulary. Think of this like adding a join to a mySQL query.

For more info, take a look at Views relationship using taxonomy
> 2 votes

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


# Question
Title: Run DB query and fetch fields in block--block--ID.tpl.php
I need to run Database query and fetch the fields in my block named **block--block--45.tpl.php**.

How can I get subdomain table field values to my block tpl(block--block--45.tpl.php) file?

I tried this code in my block tpl file and its not working : **$subdomain = db\_query("select subdomain from {subdomain} where sid = :sid limit 0, 1", array(":sid" =\> $node-\>uid))-\>fetchField();**

So anyone suggest an easy way to get subdomain table field values to my block tpl file.

# Answer
It sounds like you want to enable Tokens on your site and use a token to show the subdomain name in your block, after adjusting the Input Format for the block.

There really isn't coding involved, unless the subdomain module does not provide token support (then implement hook\_token\_info).
> 1 votes

# Answer
You should NEVER run a database query from a template file. If you need some extra values from the database available to you your block you should create a process or preprocess function in your theme.

See https://www.drupal.org/docs/7/theming/overriding-themable-output/setting-up-variables-for-use-in-a-template-preprocess-and for more details.
> 0 votes

---
Tags: 7, database, blocks
---


# Question
Title: 8 - How do i programmatically enable a user field under manage form display and manage display?
I've programmatically added a user field but i can't find a way to programmatically enable the field under 'manage form display' and 'manage display'.

I tried exporting the 'entity view display' and 'entity form display' configuration as seen below but it will not allow me to install the module using this method

Entity Form display:

```
uuid: ecd2bd45-26ec-4fee-835a-eedc20a1dbf9
langcode: en
status: true
dependencies:
  config:
    - field.field.user.user.field_birthdate_pixelpin
    - field.field.user.user.field_country_pixelpin
    - field.field.user.user.field_family_name_pixelpin
    - field.field.user.user.field_gender_pixelpin
    - field.field.user.user.field_given_name_pixelpin
    - field.field.user.user.field_nickname_pixelpin
    - field.field.user.user.field_phone_number_pixelpin
    - field.field.user.user.field_postal_code_pixelpin
    - field.field.user.user.field_region_pixelpin
    - field.field.user.user.field_street_address_pixelpin
    - field.field.user.user.field_town_city_pixelpin
    - field.field.user.user.user_picture
    - image.style.thumbnail
  module:
    - image
    - user
_core:
  default_config_hash: LLAieeozVsoZDb-2PbFxRJpQqnKmpR7-4OoRJnduz-U
id: user.user.default
targetEntityType: user
bundle: user
mode: default
content:
  account:
    weight: 0
    settings: {  }
    third_party_settings: {  }
  contact:
    weight: 3
    settings: {  }
    third_party_settings: {  }
  field_birthdate_pixelpin:
    type: string_textfield
    weight: 5
    settings:
      size: 60
      placeholder: ''
    third_party_settings: {  }
  field_country_pixelpin:
    type: string_textfield
    weight: 6
    settings:
      size: 60
      placeholder: ''
    third_party_settings: {  }
  field_family_name_pixelpin:
    type: string_textfield
    weight: 7
    settings:
      size: 60
      placeholder: ''
    third_party_settings: {  }
  field_gender_pixelpin:
    type: string_textfield
    weight: 8
    settings:
      size: 60
      placeholder: ''
    third_party_settings: {  }
  field_given_name_pixelpin:
    type: string_textfield
    weight: 9
    settings:
      size: 60
      placeholder: ''
    third_party_settings: {  }
  field_nickname_pixelpin:
    type: string_textfield
    weight: 10
    settings:
      size: 60
      placeholder: ''
    third_party_settings: {  }
  field_phone_number_pixelpin:
    type: string_textfield
    weight: 11
    settings:
      size: 60
      placeholder: ''
    third_party_settings: {  }
  field_postal_code_pixelpin:
    type: string_textfield
    weight: 12
    settings:
      size: 60
      placeholder: ''
    third_party_settings: {  }
  field_region_pixelpin:
    type: string_textfield
    weight: 13
    settings:
      size: 60
      placeholder: ''
    third_party_settings: {  }
  field_street_address_pixelpin:
    type: string_textfield
    weight: 14
    settings:
      size: 60
      placeholder: ''
    third_party_settings: {  }
  field_town_city_pixelpin:
    type: string_textfield
    weight: 15
    settings:
      size: 60
      placeholder: ''
    third_party_settings: {  }
  language:
    weight: 2
    settings: {  }
    third_party_settings: {  }
  timezone:
    weight: 4
    settings: {  }
    third_party_settings: {  }
  user_picture:
    type: image_image
    settings:
      progress_indicator: throbber
      preview_image_style: thumbnail
    third_party_settings: {  }
    weight: 1
hidden: {  }

```

Entity View display:

```
uuid: 7ae755fd-5988-446f-beb5-2c9725b10c30
langcode: en
status: true
dependencies:
  config:
    - field.field.user.user.field_birthdate_pixelpin
    - field.field.user.user.field_country_pixelpin
    - field.field.user.user.field_family_name_pixelpin
    - field.field.user.user.field_gender_pixelpin
    - field.field.user.user.field_given_name_pixelpin
    - field.field.user.user.field_nickname_pixelpin
    - field.field.user.user.field_phone_number_pixelpin
    - field.field.user.user.field_postal_code_pixelpin
    - field.field.user.user.field_region_pixelpin
    - field.field.user.user.field_street_address_pixelpin
    - field.field.user.user.field_town_city_pixelpin
    - field.field.user.user.user_picture
    - image.style.thumbnail
  module:
    - image
    - user
_core:
  default_config_hash: L2mtwGWH_7wDRCMIR4r_Iu_jmvQ10DV1L8ht8iNZ5qY
id: user.user.default
targetEntityType: user
bundle: user
mode: default
content:
  field_birthdate_pixelpin:
    type: string
    weight: 2
    label: above
    settings:
      link_to_entity: false
    third_party_settings: {  }
  field_country_pixelpin:
    type: string
    weight: 3
    label: above
    settings:
      link_to_entity: false
    third_party_settings: {  }
  field_family_name_pixelpin:
    type: string
    weight: 4
    label: above
    settings:
      link_to_entity: false
    third_party_settings: {  }
  field_gender_pixelpin:
    type: string
    weight: 5
    label: above
    settings:
      link_to_entity: false
    third_party_settings: {  }
  field_given_name_pixelpin:
    type: string
    weight: 6
    label: above
    settings:
      link_to_entity: false
    third_party_settings: {  }
  field_nickname_pixelpin:
    type: string
    weight: 7
    label: above
    settings:
      link_to_entity: false
    third_party_settings: {  }
  field_phone_number_pixelpin:
    type: string
    weight: 8
    label: above
    settings:
      link_to_entity: false
    third_party_settings: {  }
  field_postal_code_pixelpin:
    type: string
    weight: 9
    label: above
    settings:
      link_to_entity: false
    third_party_settings: {  }
  field_region_pixelpin:
    type: string
    weight: 10
    label: above
    settings:
      link_to_entity: false
    third_party_settings: {  }
  field_street_address_pixelpin:
    type: string
    weight: 11
    label: above
    settings:
      link_to_entity: false
    third_party_settings: {  }
  field_town_city_pixelpin:
    type: string
    weight: 12
    label: above
    settings:
      link_to_entity: false
    third_party_settings: {  }
  member_for:
    weight: 1
    settings: {  }
    third_party_settings: {  }
  user_picture:
    type: image
    weight: 0
    settings:
      image_style: thumbnail
      image_link: content
    third_party_settings: {  }
    label: hidden
hidden: {  }

```

Is there a way to do this in Drupal 8?

i tried to edit the existing fields using this but didn't work:

```
function openid_connet_entity_edit(){
  \Drupal::entityTypeManager()
  ->getStorage('entity_view_display')
  ->load('user.user.default')
  ->setComponent('field_birthdate_pixelpin', [
      'format' => 'plain text'
    ])->save();

  \Drupal::entityTypeManager()
  ->getStorage('entity_form_display')
  ->load('user.user.default')
  ->setComponent('field_birthdate_pixelpin', [
      'Widget' => 'textfield'
    ])->save();
}

```

# Answer
You can't install view modes or form modes that already exists. You could try to overwrite them by parsing the yaml and store the complete content in the configuration, but a better approach would be to only add the new fields to preserve any changes that the site owner could have made.

You can add fields with setComponent() in the configuration of the view mode:

```
\Drupal::entityTypeManager()
  ->getStorage('entity_view_display')
  ->load('user.user.default')
  ->setComponent('field_example', [
        'label' => 'hidden',
        'type' => 'string',
        'settings' => ['...' => '...'],
    ])->save();

```

or form mode:

```
\Drupal::entityTypeManager()
  ->getStorage('entity_form_display')
  ->load('user.user.default')
  ->setComponent('field_example', [
   ...

```

**Example**

core.entity\_view\_display.user.user.default.yml

```
content:
  field_birthdate_pixelpin:
    type: string
    weight: 2
    label: above
    settings:
      link_to_entity: false
    third_party_settings: {  }

```

PHP

```
\Drupal::entityTypeManager()
  ->getStorage('entity_view_display')
  ->load('user.user.default')
  ->setComponent('field_birthdate_pixelpin', [
      'type' => 'string',
      'label' => 'above',
      'settings' => ['link_to_entity' => 'false'],
  ])->save();

```

If you set no weight, the field will be appended under the last field.
> 10 votes

---
Tags: 8, users, entities
---


# Question
Title: Do you really need SSL on local dev environments?
If a Drupal site is running on production with https, is there any reason why this should be done also on local dev like xampp? Just wondered about so many people desperately trying to run SSL on localhost (independently of Drupal).

# Answer
> 2 votes
It depends on the site.

Some third party tech, services, etc require SSL to be enabled and working for basic functionality. Meaning for those cases any/all development/staging environments would need to be running SSL for development and quality assurance.

In all cases the closer your development environments are to the live environment the better quality assurance can be.

# Answer
> 1 votes
Maybe?

If you load something from HTTPS from a non HTTPS site, you might encounter cross domain or same origin errors.

It depends on what you're building and how.

If you need HTTPS locally, Acquia has their dev desktop tool, and I'm pretty sure HTTPS is enabled with a checkmark.

Download - https://www.acquia.com/download

---
Tags: 8, ssl
---


# Question
Title: Clearing Acquia Varnish Cache when any content gets updated
I have a drupal 7 site on acquia and everytime one of my editor makes changes to content, I have to manually clear the varnish cache for him. Is there a way to fire this clear cache everytime he saves a content? Also clear cache doesnt work, as I have to goto the acquia admin panel and click on clear varnish cache. What are some work arounds to this?

I actually have the Acquia purge button, is this what is used to clear the varnish cache? But it seems like that is failing:

# Answer
> 0 votes
Not sure if this module would work for you, https://www.drupal.org/project/acquia\_flush\_varnish

Another module that you could check, https://www.drupal.org/project/acquia\_purge

If neither one works, you can leverage Acquia's API.

> `DELETE /sites/:site/envs/:env/domains/:domain/cache`

An example from them,

> `curl -s -u user:pass -X DELETE \
>  https://example.com/v1/sites/site/envs/prod/domains/example.com/cache.json`

> `# Replace 'sitename' below with the appropriate value.
>  curl -X PURGE -H "X-Acquia-Purge:sitename" -H "Accept-Encoding: gzip" http://example.com/path/to/page`

A module that executes that when saving nodes, or a particular content type, should be easy.

# Answer
> 0 votes
It seems that you MUST have drush setup with alias to do a **drush ap-forget** command targeting the production servers. Setting up aliases isn't that easy.

After running that command the page now renders properly:

---
Tags: caching, proxies, acquia-cloud
---


# Question
Title: Cloning a Drupal website without content
Drupal 8 ships with the new Configuration Management System. This system checks the sites UUID and only allows imports of configuration if the uuid is the same.

This means, your steps to create a new environment is:

1. dump db from existing environment
2. import db to new environment
3. import config in new environment

This however does not work in cases where one is not allowed to access Production data. How would one in this case then handle the creation of new environments?

Same goes for a new developer entering the project, he has to import a DB from prob/stg. But what if this db multiple GB's big. You are now running a multi GB website on your local machine.

In symfony we "solve" this with fixtures to create dummy data. this can then be used to create new environments from scratch on the fly. In Drupal 7 this was also possible with features.

So my question is, how does one do this in Drupal 8 if cloning the existing environment is forbidden? How do you sync configuration between these environments?

# Answer
> 3 votes
Have a look at Config Installer. It allows you to the initial install already based on your exported configuration and so replaces step 2 and 3.

One problem is that you might notice that there is more "content" or non-configuration stuff than you'd think (unfortunately). Menu Links created in the UI are content, aliases are content, translations are stored in a separate table too, Taxonomies/Terms as well (Fine for something like a free-tagging field, but they are often used to define fixed structures as well, like sections on a news site).

---
Tags: 8, configuration, deployment
---


# Question
Title: How to rewrite the output of $content inside a pane template?
I am trying to reformat / rewrite the output of pane content inside my panel template.

Here is what I have:

```
panels-pane--panels-mini--some-name.tpl

```

Inside this file I have:

```
print render($content)

```

I need to break apart the items inside of content. What is the best way to go about doing this?

# Answer
> 0 votes
Look in your panels module the function template\_preprocess\_panels\_pane() you can use this.

http://www.drupalcontrib.org/api/drupal/contributions%21panels%21panels.module/function/template\_preprocess\_panels\_pane/7

http://www.drupalcontrib.org/api/drupal/contributions!panels!panels.module/function/template\_preprocess\_panels\_pane/8

---
Tags: 7, theming, panels
---


# Question
Title: How attach a Custom Field do it by code to a Custom Type Page
I create by YAML files a Field Custom, using the next documentation:

https://www.drupal.org/docs/8/api/entity-api/programming-custom-fields-into-your-content-type

In this tutorial attach the field to Custom Type "car\_brand" created by code, in my case I need attach the custom field to the Custom Type "page", he come default in drupal.

How I can attach the field to "page" content type?

Thanks a lot.

# Answer
You just have to create or change the file attaching the field to instead be attached to the page content type:

First we'll have to rename it: `field.field.node.page.field_brand_information.yml`

Secondly, we should be fine just changing all the references from car\_brand to the page bundle instead:

```
# field.field.node.page.field_brand_information.yml
langcode: en
status: true
dependencies:
  config:
    - field.storage.node.field_brand_information
    - node.type.page
  module:
    - text
id: node.page.field_brand_information
field_name: field_brand_information
entity_type: node
bundle: page
label: 'Brand Information'
description: 'More specific information about the car brand'
required: false
translatable: false
default_value: {  }
default_value_callback: ''
settings:
  display_summary: false
field_type: text_with_summary

```

Generally this approach is quite tedious and I agree as also pointed out in the article that you rather do it through the UI and then export the files appropriately.
> 0 votes

---
Tags: 8, entities
---


# Question
Title: How to import config and content using config import and hook_update_N
Background: I have config read-only setup on non-development environments. So all configurations (including enabled modules) are created and exported from development site and imported to different environment.

Problem: I need few new content entity types to be imported and add content of those types in database update (i.e. hook\_update\_N()).

As per https://www.drupal.org/node/2762235, all database updates should run before configuration import. Since my entity definitions are in configuration, hook\_update\_N throws fatal that entity types do not exist. I can run config-import after hook\_update\_N, but it can cause other problems (as mentioned in above d.o issue).

How to import configuration and content in this case?

# Answer
Don't add content using hook\_update\_N() there's not really anyway to make that work if the entity types are in config. What you can do is just use something like default content and add you own step to config import to look to see if any installed modules provide default content and create that.
> 2 votes

# Answer
One of the workaround is to run database update (hook\_update\_N) before and after configuration import. In hook\_update\_N check if your configuration changes are available. In my case, I just need to check if the new module is enabled:

```
function playground_deploy_update_8001() {
   if (!\Drupal::moduleHandler()->moduleExists('content_bar')) {
     throw new Exception('Update depends on Content Bar module which is not enabled.');
   }
  // Content import/add code here.
}

```

This way, the first database update call throws error and proceed to config import. second database update imports the content properly.
> 0 votes

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


title: How do I modify /user to a custom URL?

text:
# Question
Title: How do I modify /user to a custom URL?
I have some small Drupal 7 sites that don't require me to log in all the times, and there are no users. I would like to change the user login path to something else to deter bots targeting Drupal installations on the /user path.
How can I achieve this?

I can add a CAPTCHA, but I want to change the path too.

# Answer
See the Rename Admin Paths module. The purpose of this module is to secure drupal backend by overriding admin path. You can change user/login to something like member/login. I would also suggest adding a redirect in your htaccess to the standard user/login user/register. This way Drupal doesn't also have to serve up the 404 when a bot tries to access those pages. Huge performance savings.

EDIT: Thinking about this further, you don't need an extra module at all. Just add an alias at `/admin/config/search/path/add` for user/login, user/register etc, then just add redirects in your htaccess for the old aliases.
> 4 votes

# Answer
1.You can render login form on any site or in any block like this:

```
$form = drupal_get_form("user_login");
$form = drupal_render($elements);
print $form;

```

You then just need to set proper alias for this page.

2.`hook_preprocess_page(&$variables)`.

```
$current_path = current_path();
 $current_alias = drupal_get_path_alias($current_path);
 if($current_alias == 'user'){
   drupal_goto('my-url');
 }

```
> 2 votes

# Answer
I have a quick and easy solution I use for this scenario with no modules required. Use htaccess to redirect any visitors to user or user/login to a 404 (or I redirect them to a hidden page that logs their IP address so I can track how often they visit). Then when you want to login just user a bogus parameter in the url like /user/login/12345 This will send 99% of these spam bots off into space :)
> 1 votes

# Answer
You have a couple approaches to change the "user" Drupal path to "my-url":

First, you imitate the way Drupal defines the "user" path on user core module. In that way your "my-url" page will have same behavior than the original one.

Then, to complete the work you will need to redirect all "user" requests to your "my-url" path. To do that you can use custom code by using the hook\_menu\_site\_status\_alter() hook or you could use the redirect module.

Here's a quick implementation with custom code:

```
/**
 * Implements hook_menu().
 */
function yourmodule_menu() {

  // Registration and login pages.
  $items['my-url'] = array(
    'title' => 'User account',
    'title callback' => 'user_menu_title',
    'page callback' => 'user_page',
    'access callback' => TRUE,
    'file' => 'user.pages.inc',
    'weight' => -10,
    'menu_name' => 'user-menu',
    'file path' => drupal_get_path('module', 'user'),
  );

  return $items;
}

/**
 * Implements hook_menu_site_status_alter().
 */
function yourmodule_menu_site_status_alter(&$menu_site_status, $path) {
  if ($path == 'user') {
    drupal_goto('my-url');
  }
}

```

Note: the redirect module is not integrated with features module. If you want to propagate automatically this change to all your environments I suggest you to use custom code.
> 1 votes

# Answer
Example:

```
/**
 * Implements hook_url_outbound_alter().
 */
function custom_module_url_outbound_alter(&$path, &$options, $original_path) {
  // Alter paths for login and sign-up pages.
  if ($path === 'user/login' || $path === 'user/sign-up') {
    $path = 'omfg';
  }
}

```
> 0 votes

---
Tags: 7, routes
---


# Question
Title: How do I redirect from an existing file?
I have the Redirect module installed, but when I add a redirect from an existing file to a new file, the redirect doesn't activate.

I did some digging and found a post suggesting that Drupal can't redirect a file if it already exists, it can only redirect from 404 or pages. Is this true? Is there really no way to redirect from an existing file?

And if it is true, how do I delete the file? There doesn't seem to be a way to delete a file once it is uploaded. The file was originally attached to a content item but that content has since been deleted.

# Answer
> 5 votes
The redirect rules in .htaccess that cause Drupal to be fired up only happen if/when an actual file doesn't exist. For example, if I have a file in my webroot named file.txt, and I go to example.com/file.txt, Drupal will not start, as the file exists. If that file does not exist, Drupal will be fired up, and show a 404 page (unless you have an alias in Drupal for the path /file.txt). You have said the file exists on your system, which means Drupal is not being started up when someone accesses that file, and therefore the redirect module will not work.

As for how to delete the file, you say the content item has been deleted. This should also result in the file being deleted, though it does not appear that it was. I'd do a search through the {file\_managed} table in the database to make sure it's not still in there for some reason - maybe the file is still attached to a different piece of content or something. If you're absolutely sure the file does not exist in Drupal anymore, then you can log into your server (ftp, ssh etc) and manually delete the file.

---
Tags: files, redirection
---


# Question
Title: Is there a way to trigger migration imports from the admin UI?
I want to use module WordPress Migrate to import content from WordPress into my new Drupal 8 website. I can use the module's button "+Add import from WordPress" appearing on page admin/structure/migrate to create a new import group from a WordPress XML file. That is working alright.

After I create that Migration group, I can enter its details page. It will then display all migrations I may run from Wordpress.

What I can't do through admin interface is actually running the import. It is said that the absolute best option for this is running the import script on Drush and I can do that on my Docker local environment by running:

```
drush mi --all

```

I could also specify the name of the import group I want to use, but this is not the point here.

My question is: although it is not recommended because a PHP script could timeout etc., is it possible to run the import from within UI? I will import ~ 200 posts from Wordpress, which is not a daunting task for the website and I don't see any risk for script timeout.

Anyway, I can't find a command button or link to trigger the import process from UI. Why do I want to do that? Because my website will be hosted on a shared host where I don't have access to Drush commands.

In case such an option isn't available, what would you say are my options here? Create a custom module that would run this import only once? Is this a simple task to take over?

# Answer
A general migration runner in the UI is not yet implemented - the issue to add this is at https://www.drupal.org/node/2470882.
> 1 votes

---
Tags: 8, migrations
---


title: Drupal to Drupal migration of url alias

text:
# Question
Title: Drupal to Drupal migration of url alias
How can I do a Drupal to Drupal migrate that includes the migration of the "url alias"?

# Answer
> 1 votes
The field name (on both source and destination sides) for path aliases is 'path'. As Jaypan says, migrate\_d2d should be mapping that for you by default.

---
Tags: 7, migrations
---


# Question
Title: Tokens for taxonomy term parents in Pathauto
I am trying to find the correct tokens to use for a Pathauto pattern **in Drupal 8**.

In Drupal 7, I have a Pathauto module pattern that creates a URL alias with a node's term and parent term.

So if the node had a Term reference of *Health -\> Diet*. The URL would be `health/diet/node-title`.

The pattern to generate this is `[node:field-topic:0:parents:join-path]/[node:field-topic:0]/[node:title]`

Note the `:0` is because the Term reference field allows multiple values.

# Answer
> 10 votes
I just tested the tokens that I suggested in the comments with field\_tags on articles and it works perfectly, no idea what your problem is, make sure you use the latest versions of pathauto and token.

Token: `/articles/[node:field_tags:0:entity:parents:join-path]/[node:field_tags:0:entity]/[node:title]`

Tag hierachy: A \> B \> C

Alias for an article tagged with C: `/articles/a/b/c/pathauto-test`

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


# Question
Title: Unable to post new forum topics in Drupal site
When I try to post a new forum topic getting this error

Fatal error: Allowed memory size of 157286400 bytes exhausted (tried to allocate 91 bytes) in /sai/vij/modules/field/field.attach.inc on line 696

i have a free space of 4389 MB in server. and I given a memory\_size as -1 in php.info file.

```
     Any ideas for implementing this in drupal is appreciated.

```

# Answer
Yes i think @No Sssweat is right. You need to increase PHP memory limit.

`ini_set('memory_limit', '256M');` in your **sites/default/settings.php** file.

Increase PHP memory limit

Increase PHP's memory limit, e.g. to increase it to 256M you could try adding:

```
memory_limit = 256M to your server's main php.ini file (recommended, if you have access)
memory_limit = 256M to a php.ini file in the Drupal root
ini_set('memory_limit', '256M'); in your sites/default/settings.php file
php_value memory_limit 256M in your .htaccess file in the Drupal root

```
> 1 votes

---
Tags: 7, nodes
---


# Question
Title: How to let a role to change field formatter under view mode?
I don't mean to change view modes, I mean to change fields' formatters arbitrarily by some roles under the same view mode.

# Answer
Your question was a bit unclear.
But for what I understood, try in this page:

> yourwebsite/admin/config/content/formats

To edit permissions of roles, go here:

> yourwebsite/admin/people/permissions
> 0 votes

---
Tags: entities
---


title: Can't install experimental modules

text:
# Question
Title: Can't install experimental modules
A follow up to this thread: Can't install experimental modules

I've installed Drupal 8.2.5 two times on my server. First with the "minimal installation" option, and after that with the "normal installation" option. In both cases the installation worked without any errors. But in both cases I can't install experimental modules. I set the check mark next to an experimental module, then click install, the site refreshes and nothing changes. I can install other modules just fine. Since I must upgrade an existing Drupal 7 installation, I need the experimental Migrate modules.

No error messages are given, neither in "reports" nor on server level. Does someone know why this pre-alpha-like error occurs and how to avoid it?

# Answer
> 0 votes
Use drush to install it.

In case that don't work, try installing only BigPipe module to see if it is really a Core(experimental) modules problem or it's just some modules that are problematic and still need more development for drupal8 application. As it is written here the only stable experimental module is BigPipe.

---
Tags: 8, migrations
---


# Question
Title: How do I delete cookies when users log out?
How do I delete cookies when users log out? How can I do this with out modifying any core module?

# Answer
Imlement hook\_user\_logout($account) and call user\_cookie\_delete($cookie\_name).

For example:

```
function mymodule_user_logout($account) {
  user_cookie_delete('name');
  user_cookie_delete('mail');
  user_cookie_delete('homepage');
}

```
> 4 votes

---
Tags: 8, users, sessions, cookies
---


# Question
Title: Is it possible to define a FieldFormatter as a service
I need the 'language\_manager' service inside a custom FieldFormatter. I'd prefer not to use `\Drupal::service('language_manager')`.

Is there a special tag for FieldFormatters, or any other method to define it as a service?

# Answer
> 4 votes
You don't need to define your FieldFormatter as a service. FieldFormatters are instantiated inside the FormatterPluginManager's createInstance method (FormatterPluginManager::createInstance) which calls a create method on the formatter plugin object, passing a $container object as a parameter.

But this happens only if your FieldFormatter implements the \Drupal\Core\Plugin\ContainerFactoryPluginInterface. From then on, you are able to inject the service inside your FieldFormatter.

# Answer
> 1 votes
You can see example CommentDefaultFormatter.php. You need method **create** and **\__construct** like this:

```
<?php

namespace Drupal\mymodule\Plugin\Field\FieldFormatter;

use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

class MymoduleFieldFormatter extends FormatterBase implements ContainerFactoryPluginInterface {

  /**
   * @var \Drupal\Core\Language\LanguageManagerInterface
   */
  protected $languageManager;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $plugin_id,
      $plugin_definition,
      $configuration['field_definition'],
      $configuration['settings'],
      $configuration['label'],
      $configuration['view_mode'],
      $configuration['third_party_settings'],
      $container->get('language_manager')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, $label, $view_mode, array $third_party_settings, LanguageManagerInterface $language_manager) {
    parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $label, $view_mode, $third_party_settings);
    $this->languageManager = $language_manager;
  }

}

```

---
Tags: 8, entities, dependency-injection
---


# Question
Title: How to turn a menu tree into an associative array?
I've dig into Drupal menu core to find out a way to build an associative array from a menu tree(eg,the account menu) so that I can output the data as json format. But it seems not possible to do this with Drupal 8. The info I need from a menu tree include title, description, url, and I also need to know whether it has sub menu and if it's enabled. All this can be easily achieved using `menu_build_tree()` function in Drupal 7. Please understand I tried the so-called Drupal 8 equivalent of `menu_build_tree()` (`\Drupal::menuTree()`;) but it just gives me large object using which I don't know how to extract the data I need.

# Answer
You can load up the menu tree with `MenuLinkTree::load`, which will give you an array of menu links to work with. From there it's just a matter of looping through and getting what you need, e.g.

```
$tree = \Drupal::menuTree()->load('main', new \Drupal\Core\Menu\MenuTreeParameters());
foreach ($tree as $item) {
  $title = $item->link->getTitle();
  $url_obj = $item->link->getUrlObject();
  $has_children = $item->hasChildren;
  // etc...
}

```

The `link` is a `MenuLinkInterface`, each item itself is a `MenuLinkTreeElement`.

It would be preferable to inject the `menu.link_tree` service if possible, rather than getting it from `\Drupal`.
> 18 votes

# Answer
I'm quite late, but maybe helps someone looking for answers, here's my solution for generating recursive array from menu items.

```
private function generateSubMenuTree(&$output, &$input, $parent = FALSE) {
$input = array_values($input);
foreach($input as $key => $item) {
  //If menu element disabled skip this branch
  if ($item->link->isEnabled()) {
    $key = 'submenu-' . $key;
    $name = $item->link->getTitle();
    $url = $item->link->getUrlObject();
    $url_string = $url->toString();

    //If not root element, add as child
    if ($parent === FALSE) {
      $output[$key] = [
        'name' => $name,
        'tid' => $key,
        'url_str' => $url_string
      ];
    } else {
      $parent = 'submenu-' . $parent;
      $output['child'][$key] = [
        'name' => $name,
        'tid' => $key,
        'url_str' => $url_string
      ];
    }

    if ($item->hasChildren) {
      if ($item->depth == 1) {
        $this->generateSubMenuTree($output[$key], $item->subtree, $key);
      } else {
        $this->generateSubMenuTree($output['child'][$key], $item->subtree, $key);
      }
    }
  }
}

```

And call that function with

```
//Get drupal menu
$sub_nav = \Drupal::menuTree()->load('sub-navigation', new \Drupal\Core\Menu\MenuTreeParameters());
//Generate array
$this->generateSubMenuTree($menu_tree2, $sub_nav);

```
> 10 votes

---
Tags: 8, navigation
---


# Question
Title: How to create a menu child of an other menu?
How can I create a menu child of an other menu. Drupal menu are links to pages or an other content type. I want a main menu that can expand sub menus by clicking on a menu item. So, there is a module that can create menu children of a menu?

# Answer
You can use the Menu block module

> .. allows you to display blocks of menu links starting with any desired level of a menu and limited to any desired depth.
>
> .. you can choose to expand all menu links with children or to root the menu tree to a specific menu item.
> 0 votes

---
Tags: 7, navigation
---


# Question
Title: How to alter default value of select in webform
Using drupal 7 and Webform (both up2date), how can I alter the default value of a "Select options" field?

I tried to do this:

```
function mymodul_webform_component_render_alter (&$element, &$component) {
if( $element['#type'] == 'select' &&
      $element['#title'] == 'field1' ) {
$element['#default_value'] = 'bar,foo';}
}

```

But it's not working...

I can make it work with a single default value if I set the field to "Listbox", what I don't want. But I still can bypass this "if" statement... But still can't set the default value to multiple choices

regards

# Answer
> 1 votes
For multiple selects use an array for the default value:

```
$element['#default_value'] = array('foo', 'bar');

```

---
Tags: 7, webforms
---


# Question
Title: Error 500 when including controller file in Route
I am trying to upgrade a mailing list from drupal 7 to 8. I am getting an 500 error when I include my controller in the route file. I checked the path in both route and controllers and almost tried removing all values from the class, still I am getting the error my route file is:

```
mailing_list.admin:
  path: '/admin/structure/mailing_list'
  defaults:
_controller:'\Drupal\mailing_list\Controller\MailingListController::mailingListList'
_title: 'Mailing List'
  requirements:
_permissions: 'administer mailing lists'

```

My Controller Code is:

```
namespace Drupal\mailing_list\Controller;
class MailingListController extends ControllerBase {
  public function mailingListList() {
$output = array('table', array('header' => '1'));
}
}

```

I have removed the lines in controller function to avoid 500 error, but still I am getting 500 error.

# Answer
> 1 votes
If that is the entirety of your controller, then you are missing `use` statement for `ControllerBase`.

```
namespace Drupal\mailing_list\Controller;

use Drupal\Core\Controller\ControllerBase;

class MailingListController extends ControllerBase {
  public function mailingListList() {
    $output = array('table', array('header' => '1'));
  }
}

```

You also need to return a `Response` or renderable array from the controller method the route calls.

Example:

```
namespace Drupal\mailing_list\Controller;

use Drupal\Core\Controller\ControllerBase;

class MailingListController extends ControllerBase {
  public function mailingListList() {
    $output = [];
    $output['#markup'] = $this->t('Hello!');
    return $output;
  }
}

```

See: https://www.drupal.org/docs/8/api/routing-system/introductory-drupal-8-routes-and-controllers-example

If that does not work you need to post the full error you are getting.

---
Tags: 8, routes
---


title: Create service with argument

text:
# Question
Title: Create service with argument
I have class like this:

```
<?php

namespace Drupal\mymodule;

use Drupal\comment\CommentInterface;
use Drupal\comment\CommentManagerInterface;
use Drupal\comment\CommentStorage;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Database\Connection;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityManagerInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\Core\Session\AccountInterface;

class MyCommentStorage extends CommentStorage {

  /**
   * {@inheritdoc}
   */
  public function __construct(EntityTypeInterface $entity_info, Connection $database, EntityManagerInterface $entity_manager, AccountInterface $current_user, CacheBackendInterface $cache, LanguageManagerInterface $language_manager) {
    parent::__construct($entity_info, $database, $entity_manager, $current_user, $cache, $language_manager);
  }

}

```

and my file service:

```
services:
  comment.storage:
    class: Drupal\mymodule\MyCommentStorage
    arguments: ['@xxx','@database', '@entity.manager', '@current_user', '@cache.entity', '@language_manager']

```

I don't know add **@xxx** service to pass first argument in my method construct.I don't find any service implement interface **EntityTypeInterface**. So what's service I need add to first argument?

# Answer
> 2 votes
An entity handler class is instantiated via EntityHandlerInterface::createInstance static method, which takes the container as the first argument and the EntityTypeInterface as the second argument.

So you would not need the service and have to use the injected container to instantiate your class.

```
class MyCommentStorage extends CommentStorage implements EntityHandlerInterface {

  /**
   * {@inheritdoc}
   */
  public function __construct(EntityTypeInterface $entity_info, Connection $database, EntityManagerInterface $entity_manager, AccountInterface $current_user, CacheBackendInterface $cache, LanguageManagerInterface $language_manager) {
    parent::__construct($entity_info, $database, $entity_manager, $current_user, $cache, $language_manager);
  }

  static public function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
    return new static(
      $entity_type,
      $container->get('database'),
      // etc...
    );
  }

}

```

---
Tags: 8, symfony-services
---


# Question
Title: Normal View creates form with hidden inputs?
Ive created a view which im rendering in a content type TPL file with this:

```
<?php print views_embed_view('shows_taxonomy_term_links', "block_1"); ?>

```

Im getting some really weird behaviour. The view is within a form element which has some hidden fields in it. Here is my View:

```
$view = new view();
$view->name = 'shows_taxonomy_term_links';
$view->description = 'A view to emulate Drupal core\'s handling of taxonomy/term.';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Shows taxonomy term links';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['query']['options']['query_comment'] = FALSE;
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'none';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'entity';
$handler->display->display_options['row_options']['view_mode'] = 'teaser';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
/* Field: Draggableviews: Content */
$handler->display->display_options['fields']['draggableviews']['id'] = 'draggableviews';
$handler->display->display_options['fields']['draggableviews']['table'] = 'node';
$handler->display->display_options['fields']['draggableviews']['field'] = 'draggableviews';
$handler->display->display_options['fields']['draggableviews']['element_default_classes'] = FALSE;
$handler->display->display_options['fields']['draggableviews']['hide_alter_empty'] = FALSE;
$handler->display->display_options['fields']['draggableviews']['draggableviews']['handler'] = 'draggableviews_handler_fieldapi';
$handler->display->display_options['fields']['draggableviews']['draggableviews']['hierarchy_handler'] = 'draggableviews_hierarchy_handler_native';
$handler->display->display_options['fields']['draggableviews']['draggableviews']['ajax'] = 0;
$handler->display->display_options['fields']['draggableviews']['draggableviews']['draggableviews_handler_fieldapi'] = array(
  'field' => 'field_data_field_order_on_show_page:field_order_on_show_page_value',
);
/* Field: Content: Order on show page */
$handler->display->display_options['fields']['field_order_on_show_page']['id'] = 'field_order_on_show_page';
$handler->display->display_options['fields']['field_order_on_show_page']['table'] = 'field_data_field_order_on_show_page';
$handler->display->display_options['fields']['field_order_on_show_page']['field'] = 'field_order_on_show_page';
$handler->display->display_options['fields']['field_order_on_show_page']['settings'] = array(
  'thousand_separator' => ' ',
  'prefix_suffix' => 1,
);
/* Field: Content: Type */
$handler->display->display_options['fields']['type']['id'] = 'type';
$handler->display->display_options['fields']['type']['table'] = 'node';
$handler->display->display_options['fields']['type']['field'] = 'type';
/* Sort criterion: Content: Order on show page (field_order_on_show_page) */
$handler->display->display_options['sorts']['field_order_on_show_page_value_1']['id'] = 'field_order_on_show_page_value_1';
$handler->display->display_options['sorts']['field_order_on_show_page_value_1']['table'] = 'field_data_field_order_on_show_page';
$handler->display->display_options['sorts']['field_order_on_show_page_value_1']['field'] = 'field_order_on_show_page_value';
/* Contextual filter: Content: Has taxonomy term ID (with depth) */
$handler->display->display_options['arguments']['term_node_tid_depth']['id'] = 'term_node_tid_depth';
$handler->display->display_options['arguments']['term_node_tid_depth']['table'] = 'node';
$handler->display->display_options['arguments']['term_node_tid_depth']['field'] = 'term_node_tid_depth';
$handler->display->display_options['arguments']['term_node_tid_depth']['default_action'] = 'default';
$handler->display->display_options['arguments']['term_node_tid_depth']['exception']['title_enable'] = TRUE;
$handler->display->display_options['arguments']['term_node_tid_depth']['title_enable'] = TRUE;
$handler->display->display_options['arguments']['term_node_tid_depth']['title'] = '%1';
$handler->display->display_options['arguments']['term_node_tid_depth']['default_argument_type'] = 'taxonomy_tid';
$handler->display->display_options['arguments']['term_node_tid_depth']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['term_node_tid_depth']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['term_node_tid_depth']['summary_options']['items_per_page'] = '25';
$handler->display->display_options['arguments']['term_node_tid_depth']['specify_validation'] = TRUE;
$handler->display->display_options['arguments']['term_node_tid_depth']['validate']['type'] = 'taxonomy_term';
$handler->display->display_options['arguments']['term_node_tid_depth']['depth'] = '0';
$handler->display->display_options['arguments']['term_node_tid_depth']['break_phrase'] = TRUE;
/* Contextual filter: Content: Has taxonomy term ID depth modifier */
$handler->display->display_options['arguments']['term_node_tid_depth_modifier']['id'] = 'term_node_tid_depth_modifier';
$handler->display->display_options['arguments']['term_node_tid_depth_modifier']['table'] = 'node';
$handler->display->display_options['arguments']['term_node_tid_depth_modifier']['field'] = 'term_node_tid_depth_modifier';
$handler->display->display_options['arguments']['term_node_tid_depth_modifier']['exception']['title_enable'] = TRUE;
$handler->display->display_options['arguments']['term_node_tid_depth_modifier']['default_argument_type'] = 'fixed';
$handler->display->display_options['arguments']['term_node_tid_depth_modifier']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['term_node_tid_depth_modifier']['specify_validation'] = TRUE;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['operator'] = 'not in';
$handler->display->display_options['filters']['type']['value'] = array(
  'show_brand' => 'show_brand',
);
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = '1';

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['enabled'] = FALSE;
$handler->display->display_options['path'] = 'taxonomy/term/%';

/* Display: Feed */
$handler = $view->new_display('feed', 'Feed', 'feed');
$handler->display->display_options['enabled'] = FALSE;
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = 15;
$handler->display->display_options['style_plugin'] = 'rss';
$handler->display->display_options['row_plugin'] = 'node_rss';
$handler->display->display_options['path'] = 'taxonomy/term/%/%/feed';
$handler->display->display_options['displays'] = array(
  'page' => 'page',
  'default' => 0,
);

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'block_1');

/* Display: Block 2 */
$handler = $view->new_display('block', 'Block 2', 'block_2');
$handler->display->display_options['defaults']['style_plugin'] = FALSE;
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['columns'] = array(
  'title' => 'title',
  'draggableviews' => 'draggableviews',
  'field_order_on_show_page' => 'field_order_on_show_page',
  'type' => 'type',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'title' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'draggableviews' => array(
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'field_order_on_show_page' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'type' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
);
$handler->display->display_options['defaults']['style_options'] = FALSE;
$handler->display->display_options['defaults']['row_plugin'] = FALSE;
$handler->display->display_options['defaults']['row_options'] = FALSE;
$translatables['shows_taxonomy_term_links'] = array(
  t('Master'),
  t('more'),
  t('Apply'),
  t('Reset'),
  t('Sort by'),
  t('Asc'),
  t('Desc'),
  t('Title'),
  t('Content'),
  t('Order on show page'),
  t('Type'),
  t('All'),
  t('%1'),
  t('Page'),
  t('Feed'),
  t('Items per page'),
  t('- All -'),
  t('Offset'),
  t('« first'),
  t('‹ previous'),
  t('next ›'),
  t('last »'),
  t('Block'),
  t('Block 2'),
);

```

And this is outputted on the page:

```
<div class="view view-shows-taxonomy-term-links view-id-shows_taxonomy_term_links view-display-id-block_1 view-dom-id-13d1e8646a8723a982380a99b187d726">

      <div class="view-content">
      <div class="views-form"><form action="/tv-show/tv-show-1" method="post" id="views-form-shows-taxonomy-term-links-block-1" accept-charset="UTF-8"><div><input type="hidden" name="form_build_id" value="form-_0pe9Jy9jP9I6UJlbXsLE1DyTAVlSNbAqxzOZM28tZI">
<input type="hidden" name="form_id" value="views_form_shows_taxonomy_term_links_block_1">
  <div class="views-row views-row-1 views-row-odd views-row-first">

    <a href="/tv-show/tv-show-1/pictures/picture1">
        <div class="field field-name-field-shared-promo-image field-type-image field-label-hidden"><div class="field-items"><div class="field-item even"><img typeof="foaf:Image" src="http://myurl/sites/ciuk/files/wallpaper2-promoimage.jpg" width="311" height="248"></div></div></div>        <div class="field field-name-field-shared-promo-text field-type-text-long field-label-hidden"><div class="field-items"><div class="field-item even"><div class="owlcarousel-fields-68" style="opacity: 1; display: block;"><div class="owl-wrapper-outer"><div class="owl-wrapper" style="left: 0px; display: block;"><div class="owl-item"><div class="item-0">The Teddies Picture</div></div></div></div></div></div></div></div>    </a>

  </div>
  <div class="views-row views-row-2 views-row-even">

```

Ive also noticed the row style output in the theming information is strange:

```
Row style output: .tpl.php, --shows-taxonomy-term-links.tpl.php, --block.tpl.php, --shows-taxonomy-term-links--block.tpl.php, --default.tpl.php, --default.tpl.php, --block-1.tpl.php, --shows-taxonomy-term-links--block-1.tpl.php

```

# Answer
I think it's caused by Draggable Views 7.x-2.1

I just did a test on one of my Views and it didn't have the **views-form** form tag until I added the field **Draggableviews: Content (Content)** to it. Even in an anonymous session everything in the "view-content" div was wrapped in a form tag with an ID with the prefix **views-form-**.

I discovered this while developing a View that outputs a form in every node result and the individual forms weren't working because they were all nested in the **Draggable Views** added parent form tag.

I resolved this by applying the patch mentioned at: https://www.drupal.org/node/2495751#comment-9965493

I believe this issue has been addressed in 7.x-2.x-dev
> 3 votes

---
Tags: 7, views, theming
---


title: SQL And Drupal skips admin set up

text:
# Question
Title: SQL And Drupal skips admin set up
I filled out the Database name, Database username, password, and port number within the Drupal set up. I selected continue, then the page loads for a long time. Next, I was leaded to another page saying, Drupal already installed. Next, I clicked on View your existing site, displaying the log in for the admin. Drupal literally skipped the admin set up, resulting in not allowing me to log in as admin. Anyone is familiar with this error? Is this even an error, or the norm for Drupal (since I seen other users experiencing this errors, but no answers)?

Drupal explain the the error is the following

> The website encountered an unexpected error. Please try again later. Drupal\Core\Config\UnmetDependenciesException: Configuration objects (automated\_cron.settings, block.block.bartik\_account\_menu, block.block.bartik\_branding, block.block.bartik\_breadcrumbs, block.block.bartik\_content..

If anyone that knows this, feel free to provide some input.

# Answer
> 1 votes
You are asking a lot of questions at the same time, but I assume your main question is *How to recover from this failed installation?*

You are seeing an `UnmetDependenciesException`, which means Drupal requires stuff (has a dependency) that has not been loaded... So probably several system modules did not install properly.

That would also explain the behavior you are experiencing, your Drupal installation is broken...

Best would be to start over from scratch, remove all the files and the database tables and try again. Also verify if you have met all of the web server requirements (Drupal 7 & 8).

---
Tags: database, installation
---


# Question
Title: Determine if menu link is current/active
When rendering a menu, in the twig file, you can set a class if `item.in_active_trail` is set:

```
  {% for item in items %}
    {%
      set classes = [
        item.in_active_trail ? 'is-active',
      ]
    %}

```

However this class is applied to each link in the trail - so if you are on the third level, three links get this class.

Is there anything I can see OOTB on `item` or add to it if the menu link is the current page? I need to highlight it and not just items in the trail itself.

# Answer
Have you tried to combine it with `item.below`? I suppose (not tested) that this could be used to only apply the class to the deepest item within the active trail. The code could look something like this:

```
{% for item in items %}
  {% if item.in_active_trail and not item.below %}
    set classes = [
       'is-active',
    ]
  {% endif %}
{% endfor %}

```
> 3 votes

---
Tags: theming, 8, navigation
---


# Question
Title: How to display a custom render element after an existing one?
So I've implemented `hook_ENTITY_TYPE_view` hook.

In there I add a view mode to the `$build` array:

```
$build['sessions'] = array(
  [
    "#markup" => "<h2>Sessies</h2>",
    "content" => array(
      Drupal::entityManager()->getViewBuilder('node')->viewMultiple($nodes, 'speaker_sessions')
    )
  ]
);

```

What happends now is that this will allways be rendered before all the other content. How can I manipulate this? Adding `#weight` to this element does not seems to effect the other content.

# Answer
> 1 votes
Are you sure that code is correct?

```
$build['sessions'] = array(
  [
    "#markup" => "<h2>Sessies</h2>",
    "content" => array(
      Drupal::entityManager()->getViewBuilder('node')->viewMultiple($nodes, 'speaker_sessions')
    )
  ]
);

```

It appears you are creating 2 arrays (`array()` and `[]`). The given example `hook_ENTITY_TYPE_view()` looks like this:

```
$build['mymodule_addition'] = array(
  '#markup' => mymodule_addition($entity),
  '#theme' => 'mymodule_my_additional_field',
);

```

The problem you are likely having is because of the nested array. If you apply a weight to the inner array, it will sink to the bottom of the outer array. You however still have no control over the position of the outer array. So either use a single array and add the weight there, or use the double array as it is, but apply the weight to the outer array.

But that conflicts a bit with your question because this is not a view mode, it is just an extra render element.

---
Tags: theming, 8
---


title: Can't install experimental modules

text:
# Question
Title: Can't install experimental modules
I installed Drupal 8.1.2, but I can't install modules of the category "core (experimental)". No problem with other modules or themes for example. I get no logs and no error message. Hitting the install button just redirects me to the extend page.

I have been able to install Migrate by installing Migrate Plus, which requires Migrate, but this does not solve the issue, in particular not for the other modules in "core (experimental)". Is there anything I have to do to be able to install experimental modules?

# Answer
There's a core issue for failure to install experimental modules (or, more precisely, modules with parentheses in the group name with Suhosin): https://www.drupal.org/node/2665152
> 0 votes

---
Tags: 8, migrations
---


title: Display roles in profile?

text:
# Question
Title: Display roles in profile?
I'm trying to display roles in the default user profile (no profile2) with consistent formatting to the other fields being displayed.

In `user-profile.tpl.php` I have this:

```
<div class="profile"<?php print $attributes; ?>>
    <?php
    // var_dump($user_profile); exit;
    $account = user_load(arg(1));
    $roles = '';
    foreach ($account->roles as $rid => $role) {
        $roles .= "<li>".$role."</li>";
    }
    if (count($roles) > 0) {
        $user_profile['field_user_roles'] = array(
            '#entity_type' => 'custom',
            '#bundle' => 'custom',
            '#theme' => 'field',
            '#field_type' => 'text',
            '#title' => 'Roles',
            '#label_display' => 'above',
            '#field_name' => 'field_user_roles',
            '#markup' => '<ul>' . $roles . '</ul>',
            '#weight' => 5,
        );
    }

     ?>
  <?php print render($user_profile); ?>
</div>

```

Which is giving me this output (which is close):

The problem is that it doesn't seem to be using `#markup` to display the field.

I'm getting these errors which indicate I'm doing something wrong:

> Notice: Undefined index: #items in template\_preprocess\_field() (line 1060 of /path/to/site/modules/field/field.module).
>
> Warning: Invalid argument supplied for foreach() in template\_preprocess\_field() (line 1060 of /path/to/site/modules/field/field.module).
>
> Notice: Undefined index: #view\_mode in zurb\_foundation\_preprocess\_field() (line 311 of /path/to/site/sites/all/themes/zurb\_foundation/template.php).

I'm also using the Foundation Drupal template (v7.5) which seems to relate to the above errors.

# Answer
**Updated answer**

Scrolling through the Drupal.org module library, I discovered Role expose. I have never used it, but it seems to do the trick as well:

> Role Expose -module gives site administrators ability to expose user their own user roles. Roles are listed on user profile page. Users may be granted an option to view own roles or all users roles.

**Original answer**

Looking at the render array, I feel you misunderstood a bit (unless you have configured a field on the user object where you already put a string of all his roles, but then you would not need the logic here)...

```
$user_profile['field_user_roles'] = array(
  '#entity_type' => 'custom',          // Nope, it is 'user'.
  '#bundle' => 'custom',               // Nope, it is 'user'.
  '#theme' => 'field',                 // Probably it is not a field, but a custom render element containing markup.
  '#field_type' => 'text',             // Probably not since it probably wasn't a field.
  '#title' => 'Roles',
  '#label_display' => 'above',
  '#field_name' => 'field_user_roles', // Probably not since it probably wasn't a field.
  '#markup' => '<ul>' . $roles . '</ul>',
  '#weight' => 5,
);

```

I guess it works better if you remove some of the data (see below).

On a small side note, logic should be avoided as much as possible within template files. So I'd recommend creating a small custom module and implementing `hook_user_view_alter()`. (If you are planning on supporting only one theme, you can also place it in the theme's `template.php` file. Use the theme name as the module name.)

```
function MODULENAME_user_view_alter(&$build) {
  // Obtain the account that user_view() stored for us.
  $account = $build['#account'];

  // Prepare roles string.
  $roles = '';
  foreach ($account->roles as $rid => $role) {
    $roles .= "<li>".$role."</li>";
  }

  if (count($roles) > 0) {
    $build['modulename_user_roles'] = array( // Prefix with module name to prevent collisions.
      '#type' => 'item',
      '#title' => 'Roles',
      '#markup' => '<ul>' . $roles . '</ul>',
      '#attributes' => array('class' => 'class-one class-two'),
    );
  }
}

```

Additionally you can implement `hook_field_extra_fields()` to expose the property on `example.com/admin/config/people/accounts/display` and choose its weight within the admin interface.

```
function MODULENAME_field_extra_fields() {
  $extra['user']['user'] = array(
    'display' => array(
      'modulename_user_roles' => array( // Make sure the name matches your custom property
        'label' => t('User roles'),
        'description' => t("Lists the user's roles."),
        'weight' => 5,
      ),
    )
  );

  return $extra;
}

```

Combined, the property should have been added to the `$user_profile` array and there is no more need to override the template file.

If you want to use the item\_list, as proposed by Yogesh, your render array in `MODULENAME_user_view_alter()` should look something like this:

```
    $build['modulename_user_roles'] = array(
      '#title' => 'Roles',
      '#theme' => 'item_list',
      '#items' => $account->roles,
      '#type' => 'ul',
      '#attributes' => array('class' => 'class-one class-two'),
    );

```
> 6 votes

# Answer
You can use theme\_item\_list function to print it in lsit format, check sample below:

```
<div class="profile" <?php print $attributes; ?>>
<?php $account = user_load(arg(1)); ?>
<?php print theme('item_list', array('items' => $account->roles)); ?>
</div>

```

Or you can write your own html like below (not preferred):

```
<div class="profile" <?php print $attributes; ?>>
<?php
  $account = user_load(arg(1));

  // Below code wraps roles in <li> tag.
  $roles = '<ul><li>' . implode('</li><li>', $account->roles) . '</li></ul>';
  // Below code show roles separated by comma.
  // $roles = implode(', ', $account->roles);

  print '<ul>' . $roles . '</ul>';
?>
</div>

```
> 2 votes

---
Tags: 7, users, entities
---


title: Ajax call results in 404

text:
# Question
Title: Ajax call results in 404
I'm porting an applet (tested standalone) to embedd it into a Drupal site.

It includes some Ajax processes, which work fine in the original version.
Once adapted for Drupal, they all result in 404.

Below is a simplified excerpt of how I'm working.

**myModule.module**

```
function myModule_menu() {
  return [
    'myModule-ajax' => [
      'page callback'     => '_myModule_ajax_handle',
      'access arguments'  => ['access content'],
      'type'              => MENU_CALLBACK,
    ],
  ];
}

// ...

function _myModule_ajax_handle() {
  // here is a deliberately simplified return
  return '{"test": "Ajax result sample"}';
}

```

**JS part**

```
(function($) {

// Set common $.ajax properties.
$.ajaxSetup({
  url: 'myModule-ajax',
  //method: 'POST',
  dataType: 'json',
  error: function(jqXHR, status, error) {
    console.log(status + ': ', error);
  }
});

getSqlObj('Depts'); // -> sqlDepts

// ...

function getSqlObj(objName) {
  $.ajax({
    data: {
      ajax: 'get' + objName
    },
    success: function(response) {
      // ...
    }
  })
}

})(jQuery);

```

With Firefox devtools I can see that the right url was called, in this case:

`myModule-ajax?ajax=getDepts`

but the status is 404, and the returned data is **the fully rendered** current page, with a message replacing the current node content:

> Requested page "/mySite/fr/myModule-ajax?ajax=getDepts" not found

So I wonder not only why I get a 404 status, but also why I get this data returned.

NOTE: among a number of tries with differently expresses urls, I noticed another weirdness: at the time of `url` affectation (in `$.ajaxSetup()` above), `Drupal.settings.basePath` is undefined (in fact, `Drupal.settings` exists but is empty).
In the other hand, it contains all expected data when examined through the console just after the fail.

# Answer
> 1 votes
A post request is when you are sending information to the server and returning response data, get is just simply just grabbing data. This is an example of a post AJAX request I have working in Drupal, stripped down. It is assuming data is being passed from the ajax call into PHP then is returned back to JS.

Create your AJAX path with hook\_menu() in your custom module

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

  $items['my_ajax_path'] = array(
    'title'             => 'My Ajax path that does stuff',
    'page callback'     => 'myPageCallBack',
    'type'              => MENU_CALLBACK,
  );

  return $items;
}

```

Create your page callback for your menu defined in hook\_menu() in custom module

```
function myPageCallBack(){
 if(isset($_POST['myData'])){
   $postData = $_POST['myData']
   return drupal_json_output($postData);
 }
}

```

AJAX Call in your custom JS file (location is up to you but i find this is easy to maintain, you can add js to a page using drupal\_add\_js)

```
function call_AJAX(myVariable){
    jQuery.ajax({
      url: "/my_ajax_path?action=myPageCallBack",
      type: "POST",
      data: {myData: myVariable},
      dataType: "json",
      success: function(data){
            alert(data);
            if(data == ''){
                alert('There was an error processing the form. Please try again later.');
                return;
            }
        },
        error: function(xhr, status, error){
                console.log(xhr);
                console.log(xhr.status);
        },
    });
}

```

I stripped this out of a working example quickly and didn't test it outside of my working environment as i'm actually leaving work right now, but using the above code i can make post ajax requests no issue. Let me know if this works for you!

---
Tags: 7, ajax
---


# Question
Title: How to link a field to node title in view
I created a content type. I have three fields: title, body, city.

I added two contents.

I can see nodes at:

http://www.example.com/?q=content/we-buy-houses-nj

http://www.example.com/?q=content/we-buy-houses-va

I created a view as following: I added **title** field first (excluded from display). I selected city field. For rewrite results, change the path to "content/\[title\]"

**Result:**

I can see the city field is hyperlinked. When I click each link, I get URL as following and page can not be found:

http://www.example.com/?q=content/We%20Buy%20Houses

http://www.example.com/?q=content/We%20Buy%20Houses

How do I remove the **%20** so page can be found in my case?

# Answer
You get `%20` because the browser replaces/fixes/auto-corrects the empty space between your title with `%20` as empty spaces are not allowed in URLs.

EX: If you try to go to `drupal.org/Hello World`, browser url changes/corrects it to `drupal.org/Hello%20World`.

---

Here is another *possible* option:

Add `Path` as a field, and checkmark exclude from display.

Make sure `Content: Path` is above `Content: Cities`, if not please re-arrange it.

Then in cities, for link path put `[path]`
> 2 votes

---
Tags: views
---


# Question
Title: How to resolve the MySQL error Duplicate entry 'comment_publish_action' for key 'PRIMARY'?
I'm a beginner in Drupal. I want to import my database to my webserver and get this error when trying to do so:

> "#1062 - Duplicate entry 'comment\_publish\_action' for key 'PRIMARY'"

I don't know how to fix this error.

Here are more details about it:

> INSERT INTO `actions` (`aid`, `type`, `callback`, `parameters`, `label`) VALUES ('comment\_publish\_action', 'comment', 'comment\_publish\_action', '', 'Publish comment'), ('comment\_save\_action', 'comment', 'comment\_save\_action', '', 'Save comment'), ('comment\_unpublish\_action', 'comment', 'comment\_unpublish\_action', '', 'Unpublish comment'), ('node\_make\_sticky\_action', 'node', 'node\_make\_sticky\_action', '', 'Make content sticky'), ('node\_make\_unsticky\_action', 'node', 'node\_make\_unsticky\_action', '', 'Make content unsticky'), ('node\_promote\_action', 'node', 'node\_promote\_action', '', 'Promote content to front page'), ('node\_publish\_action', 'node', 'node\_publish\_action', '', 'Publish content'), ('node\_save\_action', 'node', 'node\_save\_action', '', 'Save content'), ('node\_unpromote\_action', 'node', 'node\_unpromote\_action', '', 'Remove content from front page'), ('node\_unpublish\_action', 'node', 'node\_unpublish\_action', '', 'Unpub\[...\]

# Answer
From the information provided in the question so far, it is hard to tell what is causing your problem (consider refining your question by editing it).

However, as an alternative, you may want to consider using the Backup and Migrate module like so:

* install that module on both Drupal sites (where you want to export from, and where you want to import to).
* use this module to create a backup in the originating Drupal site (and save it somewhere to a local file), of the relevant tables in the MySQL database.
* use this module to restore that "local file" (= backup) to import it in your target site (which is where you're currently encountering the problem.

Does this help somehow?
> 0 votes

# Answer
i had the same problem when upgrading (or after upgrading) from D6 to D7. i am guessing rule module.. go to /admin/config/system/actions/orphan, there is no orphan menu, just type 'orphan' in url. log will show that action was deleted. After visiting orphan path, importing users table error '"#1062 - Duplicate entry 'comment\_publish\_action' for key 'PRIMARY'"' was gone when importing users table to different database in my case.
> 0 votes

---
Tags: database, importing-exporting
---


title: User based node saving

text:
# Question
Title: User based node saving
I have two roles Editor and Manager. Editor can add nodes as unpublished and manager can review the nodes and approve/publish them in website.

For administration I am using default SEVEN theme for adding/editing nodes. How can i hide "Save and Publish" button to editor role only?

Can it possible by calling a template hook node\_presave? I tried below code but not worked.

```
 function seven_node_presave($node) {
    global $user;

    if (in_array('editor',$user->roles)){
        $node->status = FALSE;
    }

}

```

if any body can suggest solution for this?

# Answer
> 1 votes
> How can i hide "Save and Publish" button to editor role only?

You can use two ways.

1. Simple ways. Enable module Content Moderation in core and set permission by roles.
2. Use function hook\_form\_node\_form\_alter()

> ```
> global $user;
>
> if (in_array('editor',$user->roles)){
>    $node->status = FALSE;
> }
>
> ```

Drupal 8 have some different. Global user replace by
`\Drupal::currentUser()`

and $user-\>roles replace by

```
\Drupal::currentUser()->getRoles()

```

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


# Question
Title: How do I display the submitted data in the same page?
I created a custom form in Drupal 7. I need to display the submitted data in the same page showing the form, without using `drupal_set_message()`. Is it possible?

# Answer
You can use `$form_state['rebuild']`;

If `$form_state['rebuild'] = TRUE;` has been set then a new copy of the form is immediately built and sent to the browser. Instead of a redirect to new page.

Example:

```
function example_form_submit($form, &$form_state)
{
  // we return the submitted value to the form
  // by storing it in $form_state['storage'] and rebuilding
  $form_state['storage']['some_value'] = $form_state['values']['some_value'];
  $form_state['rebuild'] = TRUE;
}

```

You can refer https://www.drupal.org/node/2171993

Another way store the "`$form_state['values']`" in session.

Take @clive answer How to display an HTML table after the form submission on the same page as the form? as reference.
> 2 votes

---
Tags: 7, forms
---


# Question
Title: How to display specific exposed filters of a view in a block
I have a set of exposed filters in one of my views. I want display a few of them as normal exposed filters and the rest exposed filters in a block in the head region of the view. Is there a way by which I can split the exposed filters & specify the filters to be displayed in the block?

Thanks

# Answer
It's very simple.

Create a new view as a block using the Add button on top of your view admin page (Add \> Block).

In your new view Exposed Form section, click on "Exposed form in a block" and press yes. In this way a block of your exposed filters is created in your Blocks admin page (admin/structure/block).

Using the blocks admin page enable your block and place it to the region of your liking.

Doing the above steps, you will get one exposed filter group on top of your view and one exposed filters block wherever you like in your site.
> 4 votes

---
Tags: views
---


# Question
Title: How to flip order of Privatemsg thread from ASC to DESC?
When an individual private message thread is viewed, it displays the thread messages from oldest to newest, followed by the "Reply" field. I'd like to show the "Reply" field first, and then the thread messages from newest to oldest. How can I reverse the order of the page in this way? I cannot find anything in the code that would point me toward something to re-theme it in a descending order instead of ascending.

Something like this:

> \[REPLY FIELD\]
>
> \[Message on Jan 6 2017 at 11:30am\]
>
> \[Message on Jan 6 2017 at 11:05am\]
>
> \[Message on Jan 6 2017 at 10:00am\]
>
> \[Message on Jan 5 2017 at 11:45am\]

...instead of the current layout/ordering, which is like this:

> \[Message on Jan 5 2017 at 11:45am\]
>
> \[Message on Jan 6 2017 at 10:00am\]
>
> \[Message on Jan 6 2017 at 11:05am\]
>
> \[Message on Jan 6 2017 at 11:30am\]
>
> \[REPLY FIELD\]

# Answer
> Any other ways I can get it to work, outside of hacking the module?

There is no way to alter a module from another php file / module unless it provides a hook, luckily here they did.

I must be blind, right above it (line 1098), it says in the comments: `* @see hook_query_privatemsg_messages_alter()`

I found the doc hook\_query\_privatemsg\_messages\_alter. Hooks go inside modules, more specifically inside the .module file and you replace the word `hook` with the actual name of your module.

So create a custom module, inside of **mymodule.module** (Here we assume your module is called/named mymodule)

```
/**
 * Implements hook_query_privatemsg_messages_alter().
 */
function mymodule_query_privatemsg_messages_alter($query) {
   $query
     ->orderBy('pm.timestamp', 'DESC')
     ->orderBy('pmi.mid', 'DESC');
}

```

---

Side note:

Don't confuse hooks with templates\_something\_something() those go inside your template.php file. Ex: template\_preprocess\_node and you replace the word `template` with the actual name of your theme.

---

> No Sssweat, can I bother you for one other thing? I'd like to move the reply box above the message thread. I found where this is handled in the module (privatemsg.pages.inc, lines 892 and 926). How would I override those two lines (adjusting the "weight" values so that the reply box is a lower weight than the message thread) without hacking the inc file? Would it be done somehow in a custom module?

You're suppose to use hook\_privatemsg\_view\_alter

Sadly, it does not work for reply or message; even though, when I dump `dpm($content)` using Devel the array it has changed the weight. Works for pager only. Looks like this is a bug.

```
/**
 * Implements hook_privatemsg_view_alter().
 */
function mymodule_privatemsg_view_alter($content) {

    $content['pager']['#weight'] = -3; // does not work
    $content['reply']['#weight'] = -5; // does not work
    // nor it does not work when doing $content['message']['#weight'] = -5;

}

```

If I comment out the `$content['pager']['#weight']` = 3 and `$content['reply']['#weight'] = -5;` from the module, the hook works.
> 3 votes

---
Tags: 7, privatemsg
---


title: User Registration with REST

text:
# Question
Title: User Registration with REST
How do you register a user account via REST in Drupal 8?

Here's how far I've made it (not sure if this is the right direction though):

I've enabled the `Form mode` resource under `admin/config/services/rest` for POST, cookie authentication, and hal\_json and json formats. I then make a call to the site:

```
POST: http://localhost/d8/entity/entity_form_mode
Content-type: application/hal+json
Accept: application/json

```

The JSON to POST will start something like this:

```
{"_links":{}}

```

It will of course be filled in with various properties and values. What are these properties and values though? I've tried many combinations, and the furthest I've got is the server responding with this:

```
{"error":"Entity type parameter must be included in context."}

```

# Answer
> 8 votes
This now works in Drupal 8.3-x-dev. This is an example to do it from Angular:

```
  /*
   * Register new User.
   */
  register: function (email, password) {

    var defer = $q.defer();

    $http({
      method: 'POST',
      url: config.endpoint + '/user/register',
      dataType: 'json',
      data: {
        'name': {
          'value': email,
        },
        'mail': {
          'value': email,
        },
        'pass': {
          'value': password,
        }
      },
    })
      .success(function (data, status, headers, config) {
        defer.resolve(data);
      })
      .error(function (data, status, headers, config) {
        defer.reject(data);
      });

    return defer.promise;
  }

```

Make sure you enable the resource to enable user registration (I use the REST UI module).

The last step is enabling the permissions on this resource:

Now you are all set!

# Answer
> 0 votes
Not yet. =(

There is an open "Major" feature request for this:

It's currently in Drupal 8.2.x-dev, which is scheduled to be released as a beta in Aug 2016, and stable in Oct 2016.

From the issue summary: "A workaround would be to login as an admin and create a user the regular way."

---
Tags: 8
---


# Question
Title: How to easily create and reference a node / entity during creation of another one?
I have the task of attaching two entities to each other, and both may not exist yet. So what I'd like is to create the second entity along with the first one if it does not exist yet.

So in the case of having a task and attaching persons, assume I already have created a person. Then I would like to add him to the task by typing in his name. But at the same time, when editing a task and the field does not find a name, I like to receive the option to create the person entity on demand.

Are there recommendations as of how to approach this?

# Answer
The References dialog module might be an option (if you're using the references project).

> This module extends reference fields like the user and node reference fields by adding links to add, edit and search for references through a dialog. This allows for a workflow where the user can create all the references to a node at the same time as she is creating it, a process which sometimes get's a bit backwards, when a user for instance needs to create all the facts for an article.

It doesn't do exactly what you've described, but it's pretty close.
> 3 votes

# Answer
I am also adding Inline Entity Form to the list.

> Provides a widget for inline management (creation, modification, removal) of referenced entities. The primary use case is the parent -\> children one (product display -\> products, order -\> line items, etc.), where the child entities are never managed outside the parent form. Existing entities can also be referenced.

I learned of this module years after asking the question, but it works pretty good.
> 1 votes

# Answer
You can use the Entity connect (v2-rc1 and v1-rc5 release only)

> It will help you to improve the User Experience for creation of new entities or edition of linked entities on your entity reference fields.
>
> The "add a new" button will enable you to add / create a new entity. The first form will be cached then the new form will be generated. Once the new form is completed and saved the user will return to the original form.
>
> The "edit" button will take the user to the edit form of the referenced entity. Once the user is done editing, he is sent back to the previous form.

The Automatic Nodetitles module works fine with it. In addition with Entity connect you can edit existing entities.

You can read other options in: How to add "Content type B" from within "Content type A" and then display both together?
> 0 votes

---
Tags: 7, nodes, entities
---


title: Create menu tabs with views

text:
# Question
Title: Create menu tabs with views
**How can create menu views tabs of node?** In Drupal 7 i can create views like this:

>

when i visit node/1/teaser it's show good.

>

But with same setting in drupal 8.

>

when i visit node/1 show error:

> Symfony\Component\Routing\Exception\MissingMandatoryParametersException: Some mandatory parameters are missing ("arg\_0") to generate a URL for route "view.menu\_tabs.page\_1". in Drupal\Core\Routing\UrlGenerator-\>doGenerate() (line 171 of core/lib/Drupal/Core/Routing/UrlGenerator.php).

and node/1/teaser show error:

> Symfony\Component\Routing\Exception\MissingMandatoryParametersException: Some mandatory parameters are missing ("node") to generate a URL for route "entity.node.devel\_load". in Drupal\Core\Routing\UrlGenerator-\>doGenerate() (line 171 of core/lib/Drupal/Core/Routing/UrlGenerator.php).

# Answer
This is a known issue in views.

The issue is that the route parameter for entities needs to be named:

> This view will be displayed by visiting this path on your site. You may use "%" or named route parameters like "%node" in your URL to represent values that will be used for contextual filters: For example, "node/%node/feed" or "view\_path/%". The named route parameters are necessary when used within paths used by entities such as "taxonomy/term/%taxonomy\_term" or "user/%user/custom-view

This is for the first error message.

The second one is caused by the devel module. If you still get this error after renaming the route parameter, you have to check the issue queue from this module.
> 9 votes

---
Tags: views, 8, navigation
---


# Question
Title: I cannot use drupal_set_message() in a custom controller module
In a custom controller, when I try to use `drupal_set_message()`, it works only if I use the following code.

```
// The message is shown via {{ page.highlighted }}.
drupal_set_message('Test error', 'error');

return [
   '#type' => 'markup',
   '#markup' => "Welcome",
];

```

When I use the following code, it doesn't work.

```
drupal_set_message('Test error', 'error');

return [
   '#type' => 'page',
   '#markup' => "Welcome",
];

```

I need to set `#type` to *page* to be able to inject custom variables.

Can anybody help me to understand how it works?

# Answer
You might want to try the following code.

```
return [
  '#theme' => 'ctr',
  '#myvar' => 'myvalue',
];

```

The module needs also to implement `hook_theme()`.

```
/**
 * Implements hook_theme().
 */
function ctr_theme($existing, $type, $theme, $path) {
  $variables = array(
    'ctr' => array(
      'template' => 'cntr',
      'variables' => array(
        'myvar' => 'defaultvalue',
      ),
    ),
  );
  return $variables;
}

```
> 5 votes

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


title: Drupalgap in Aegir?

text:
# Question
Title: Drupalgap in Aegir?
I'm trying to use the Drupalgap module in a site created using Aegir.

Drupalgap requires I put some files in a directory called mobile-application at the base of my drupal installation. Within mobile-application is a configuration file at http://www.example.com/mobile-application/app/settings.js where I need to specify the following path:

Drupal.settings.site\_path = 'http://www.example.com';

Unfortunately as I am using Aegir's multisite setup I keep getting "Page not found". I've tried various different path settings such as;

Drupal.settings.site\_path = 'http://www.example.com/sites/www.example.com';

Drupal.settings.site\_path = 'var/aegir/platforms/drupal/sites/www.example.com';

I even tried creating a directory in called www.example.com.mobile-application and putting the contents of mobile-application inside it. That seemed to do something in that going to the url redirected me to http://www.example.com/install.php and resulted in this error; 403 Forbidden nginx

Anyone familiar with Aegir/multisite environments and Drupalgap?

# Answer
Disclaimer: I use Aegir 2.x and never use the Drupalgap but I use root base files.

Create a new platform in Aegir (don't mess with the current platform) and create a new site. After that you must have something like: `/var/aegir/platforms/platform_name/sites/new_site.com/`

If you put your files in `/var/aegir/platforms/platform_name/my_folder/my_script.js` you can access them by all sites in the platform `new_site.com/my_folder/my_script.js`
> 2 votes

# Answer
`site_path` needs to be the root URL of the Drupal site, for example, http://www.example.com, and you need to set the path to your DrupalGap platform relative to the Drupal root, for example

```
drush @example.com vset drupalgap_sdk_dir sites/all/libraries/drupalgap-sdk
drush @example.com vset drupalgap_sdk_installed 1

```

DrupalGap does not need to be in the Drupal root.
> 0 votes

---
Tags: multi-sites, aegir, javascript
---


# Question
Title: How to access personal contact form in search
Using Drupal 7. All of the people on my site have personal contact forms. When I type their name into the search bar, I get 'no results'.

I need people to be able to find users' personal contact form links by using the search function.

I'm using the core Search module and have enabled 'users' to be included in the search, but no results come up, regardless of which name I use. Site has been re-indexed, caches flushed, etc.

All users have a status of 'authenticated' and permissions have been set on 'contact' and 'search' to allow the results to show.

Any help is appreciated. Thanks.

# Answer
Okay. I was under a deadline so I came up with an annoying but functioning solution.

1) I added the Search by page module (https://www.drupal.org/project/search\_by\_page) and enabled it.2) I made a new search environment by going to admin/config/search/search\_by\_page.3) In the new search environment, I enabled all the content types I wanted the module to pull.4) How I got it to pull users' contact pages was:5) Go to the enironment I made and clicked 'edit'6) On the top right of the page are two tabs: 'General settings' and 'paths'7) I clicked on 'paths'and then clicked 'add new path'8) I opened a new browser window and navigated to the 'People' tab. I clicked on a user and selected their 'Contact' tab, and copied the path (in my case, user/number/contact9) I went back to the 'add new path' tab and pasted that info in the 'page to index' section10) I entered a page title (Contact Mr. Smith) and saved. Clicked on 'add new path' for next user.11) Repeated steps 7-11 for all 50 users.12) Re-indexed site by running cron. Voila, contact pages come up in search results.

This was a cumbersome, time-consuming way of doing this, and I'm sure there's a better solution. However, if you're pressed for time like I was, I hope this helps someone.
> 1 votes

---
Tags: 7, search, emails
---


# Question
Title: Drupal 8, save new fieldCollection items to user from a foreach loop doesn't work
My user structure have a multiple field "foo" of type "FieldCollection". From a custom module, I want create programmatically several fieldcollection item and add them to the current user.

Without any loop, when I add only one new FieldCollection item to the user, its work. But, when I want user a loop for add several FieldCollection, only the first item is added. I mean :

With some light php :

```
// In my module
    // some operations and prepare the datas structure
    foreach(datas as data){ // count(datas) = 2, by example
        $user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
        $field_collection_foo = FieldCollectionItem::create(array('field_name' => "field_foo"));
        $field_collection_foo->set("field_data",$data);
        $field_collection_foo->setHostEntity($user);
        $field_collection_foo->save();
    }

```

Then if I go to the user edit page from the back office, I see only the item datas\[0\] added, not datas\[0\] datas\[1\]

Where is my mistake ?

UPDATE (add some test) :

I think I find, I do an another $user-\>save somewhere in my module and I think its it who save the wrong value :) Ill test it

# Answer
Make sure you've configured the **cardinality** of the field collection `foo` as **unlimited** (or at least anything more than 1) under "Field settings".

Also double check the name that you are passing to the `FieldCollectionItem::create()` method. It shouldn't be the label name but the **machine name** of your `foo` field collection, which will probably be `field_foo`:

```
$field_collection_foo = FieldCollectionItem::create(
  array('field_name' => "field_foo")
);

```

This also applies to the `subfield_data` (in your field collection item):

```
$field_collection_foo->set("field_subfield_data", $data);

```
> 1 votes

---
Tags: 8, users, entities
---


# Question
Title: Is it safe to manually delete the "field_deleted_*" tables and state API data?
I'm in an odd situation where the state data that tracks which fields are deleted has a field in it that does not have its associated field\_deleted\_data\_\* table. As result, when cron tries to purge the deleted field data, an exception is thrown because it runs a query on a non-existent table.

Is OK to just delete all the remaining field\_deleted\_data\_\* and field\_deleted\_revision\_\* tables and then delete the two state API rows from the key\_value table, field.field.deleted and field.storage.deleted?

# Answer
Try deleting them cleanly first with `drush eval 'field_delete_field("yourfield")'` and run cron afterwards.
> 1 votes

---
Tags: 8, entities
---