title: drupal_set_message for anonymous user

text:
# Question
Title: drupal_set_message for anonymous user
I am having hard time displaying drupal message for anonymous users. My scenario is, I need to display message if there is certain query string and remove the query string with message. I am using following code but without success. I also tried with session variable without success.

```
 if(isset($_GET['action']) && $_GET['action'] === 'loggedoff'){
    drupal_set_message(t("We are sorry. While you have successfully authenticated, you are not yet entitled to access this site. Please ask the site administrator to provision access for you."));
    \Drupal::logger('vrpboostrap')->notice('query parameter has value loggedoff');
    $url = \Drupal::service('path.current')->getPath();
    $alias = \Drupal::service('path.alias_manager')->getAliasByPath($url);
    $alias = strtok($alias, '&');
    header('Location: '. base_path() . $alias);
    exit;
  }

```

With Session variable, I tried with:

```
if (isset($_GET['action']) && $_GET['action'] === 'loggedoff') {
    $_SESSION['vrp_action'] = 'loggedoff';
    $url = \Drupal::service('path.current')->getPath();
    $alias = \Drupal::service('path.alias_manager')->getAliasByPath($url);
    $alias = strtok($alias, '&');
    header('Location: ' . $url);
    exit;
  }
  if (isset($_SESSION['vrp_action']) && $_SESSION['vrp_action'] === 'loggedoff') {
    drupal_set_message(t("We are sorry. While you have successfully authenticated, you are not yet entitled to access this site. Please ask the site administrator to provision access for you."));
    session_unset('vrp_action');
  }

```

Can you guys advise me what am I doing wrong here and to display message for anonymous users?

# Answer
> 2 votes
The fact that you use header() and exit is most likely the problem.

You need to use response objects that you return to properly terminate the request and write the session data.

You can't do this anywhere, I'd recommend implement a Request event subscriber. `\Drupal\Core\EventSubscriber\RedirectLeadingSlashesSubscriber` is a simple example for this:

```
class RedirectLeadingSlashesSubscriber implements EventSubscriberInterface {

  public function redirect(GetResponseEvent $event) {
    $request = $event->getRequest();
    // Get the requested path minus the base path.
    $path = $request->getPathInfo();

    if (strpos($path, '//') === 0) {
      $path = '/' . ltrim($path, '/');
      $qs = $request->getQueryString();
      if ($qs) {
        $qs = '?' . $qs;
      }
      $event->setResponse(new CacheableRedirectResponse($request->getUriForPath($path) . $qs));
    }
  }

  static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = ['redirect', 1000];
    return $events;
  }

}

```

And then register that in yourmodule.services.yml:

```
redirect_leading_slashes_subscriber:
  class: Drupal\Core\EventSubscriber\RedirectLeadingSlashesSubscriber
  tags:
    - { name: event_subscriber }

```

---
Tags: 8, redirection, sessions, status-messages
---


# Question
Title: How useful is it to use the latest Composer version to maintain my sites?
I am trying to determine the best way to maintain a Drupal 8 site. I am new to Drupal, PHP and Composer, but I am learning.

I believe that my goal is to maintain my Drupal 8 site using drupal-composer/drupal-project (https://www.drupal.org/node/2718229).

I am using a shared hosting plan, but I have shell SSH access. I notice that my hosting provider already has **/opt/cpanel/composer/bin** in my command line path. That version of composer is 7 months old. (Composer version 1.1.1 2016-05-17). I have PHP 5.6.29 via the command line.

It's possible for me to install the latest version of composer (1.3) in my user directory, and then to override the hosting service's path. I want to know whether it's worth the extra trouble to do so.

Purely from the standpoint of maintaining my Drupal sites (and not from the development point of view; I won't be making my own modules any time soon), how useful/critical would it be to have the latest stable version of Composer available to me? My guess is that the hosting service won't be updating Composer often (maybe once or twice a year).

Does a somewhat out-of-date version of Composer impose limitations on how effectively it can manage Drupal and Drush updates?

# Answer
drupal-project has a composer version check built in that currently requires 1.0, so you're fine with 1.1 for now:

https://github.com/drupal-composer/drupal-project/blob/94404dcbed7fe9eb9ea8d95016b661ae6d4f9e3f/scripts/composer/ScriptHandler.php#L75

That said, more recent versions have performance improvements I think and sooner or later, there might be a problem that will force you to update, and then it will be easier if you already are using a custom more recent version. On the other side, your hosting provider might also update that version from time to time, you might want to check that with him. E.g. in case of a security issue.

But no, for now, you're not *required* to do this.
> 4 votes

---
Tags: 8, drush, composer
---


# Question
Title: See a list of fields and what content types they are attached to
I am trying to troubleshoot an issue with Panels. In one of the content panes, there are token replacements from a field.

I looked at the context menu for the page, and it was provided by a taxonomy. I'm assuming this is a field on a node, but I don't know which one.

We have a number of content types and taxonomies on the site. Is there a way, perhaps through a module, to see a list of all the fields that are on the site, and which content types they are attached to?

I'd like to avoid looking through the fields of each content type one by one, if possible.

# Answer
> 2 votes
You should be able to go to Admin \> Reports \> Field List and see a list of fields in the system and their types and what is using it.

---
Tags: entities
---


# Question
Title: Where is the documentation for core associative arrays?
I have been using Drupal for a few months now at work. I love the developer documentation, but I have to say, I feel like its incomplete -- either that, or I just don't know where to find the other half.

I see documentation for functions and hooks everywhere, but I don't see any documentation for the format of core data structures.

Example one: this page from the official docs has extensive explanation on `hook_wysiwyg_editor_settings_alter`, but it gives no complete disclosure what the `$settings` parameter can contain.

Example two: this page from the official docs has great explanation of the concept of "Render Arrays" and the functionality thereof, but has no description of the format of the associative array passed to the `render()` function, causing me to `var_dump($user_page)` for hours and come up with monstrosities like: `<?php echo $user_page["system_main"]["nodes"][$first_key]["field_objective"]["#object"]->field_targets["und"][0]["safe_value"]; ?>` on my custom .tpl.php files.

Is this information in the code itself, or somewhere else?

# Answer
Render arrays are defined (in Drupal 7) with the hook\_element\_info hook.

To see what attributes a render element can accept you can check the MODULE\_element\_info function that defined it.

For example looking at system\_element\_info we can see that the `page` render element accepts a `#show_messages` attribute and that it contains a boolean value.

For more information you can also look for the template\_preprocess\_ELEMENT function for the element.

template\_preprocess\_page in our example.
> 1 votes

---
Tags: 7, entities, hooks
---


# Question
Title: "See Also" section inline node body text
I am not sure the title of my question specifies correctly what I am looking for, but several newswebsites are using some sort of "See Also" or "Don't Miss" sections which appear between the first and second paragraphs on their articles and links to a related article. In my opinion it's a great feature as it can keep visitors longer on the website.

I have been looking to implement this on my D7 website but there seems to be no easy way to add a custom field or something in node body text. Any help would be appreciated

Here are some examples:

# Answer
> 1 votes
Really the best way to do this is with multiple fields. Rather than injecting your related content block in the middle of your body, have 3 separate fields.

1) A teaser field (contains the first paragraph)

2) Related content field (This would likely be an entity reference field. You can render the referenced node with a chosen display mode.)

3) Body field (contains the rest of the post)

The other way to do this would be by dynamically splitting your content (probably with regex) and inserting your other field in the middle. Personally, I wouldn't recommend this second option.

---
Tags: nodes, entities
---


# Question
Title: Form submit button with ajax, replace form with another one (error 500)
I am trying to turn my Form into multi-step ajax form.

I have:

```
class ProjektForm extends FormBase {

    public function getFormId() { return 'projekt_form'; }

    public function buildForm(array $form, FormStateInterface $form_state) {

        $form['title'] = array(
            '#type' => 'textfield',
            '#title' => t('Title*:'),
            '#required' => TRUE
        );
        $form['actions']['#type'] = 'actions';
        $form['actions']['submit'] = array(
            '#type' => 'submit',
            '#value' => $this->t('Add'),
            '#button_type' => 'primary',
        '#ajax' => [
            'wrapper' => 'projekt-form-ajax-id',
            'callback' => 'form_ajax_submit',
            'method' => 'replace',
            'effect' => 'fade'
        ]
        );
        $form['#prefix'] = '<div id="projekt-form-wrapper">';
        $form['#suffix'] = '</div>';
        return $form;

    }

    public function form_ajax_submit($form, $form_state) {
        return 'OK';
    }
...

```

But when I click on "Add" (submit) button and see the "please wait" Drupal icon for a while **I eventually get 500 error** for my ajax request:

Should I register somehow `form_ajax_submit`? Note that it's member function of `ProjektForm`. And I use `ProjektForm` inside my custom module which displays it from block.

What I want to do is to send the data from form via AJAX (and here I get error 500), validate it and display next form (via ajax, replacing the previous one without page reload).

# Answer
You need to add your namespaced class to the `callback` property.
For example:

```
'callback' => 'Drupal\mymodule\Form\ProjektForm::form_ajax_submit'

```

or

```
'callback' => [$this, 'form_ajax_submit']

```

You also need to make sure the wrapper and the prefix html id are the same.

Finally, after you do all that, do check your logs for more details on the error that caused the 500 response.

Good luck!
> 3 votes

---
Tags: 8, forms, ajax
---


title: Introductory text before a view

text:
# Question
Title: Introductory text before a view
I've created an *about us* page on a Drupal 8 site that is a view displaying people on my site (in alphabetical order) that were generated from a custom *member* content type.

The page is basically a "Card" type look for each person in a 3 column grid.

What is the correct way to add an introductory block of text above this view listing? Is adding a custom block of text to the header portion the best way of doing this still? I can't seem to find any recent answers to this question. Is this easy for content editors to alter afterwords?

# Answer
Under "Header" select "Add" and choose "Text area" or "Unfiltered text". Then fill in your text in the text area and click "Apply".

You will need to provide content editors access to your view in order to alter it.

Another option would be to create a custom block and to place it above the `Main page content` block. Then again, you will need to provide access to the content editors to administer blocks.
> 5 votes

# Answer
You could also try to do this the other way around. The view is 'fixed', and you want to have the node remain editable.

It appeared this did not work the way I had in mind. You want to show the view on that specific page only and because in views there is no relation between the users and the specific node, so there is no possibility to show the content only on the given node id (the view will be attached to all nodes). EVA is a great module for situations where there is such a connection though.

> For example, you might make a View that displays posts with an 'Author ID' argument, then use Eva to attach the view to the User entity type. When a user profile is displayed, the User's ID will be passed in as the argument to the view magically.

## Original answer

By creating a basic page with your introduction text and using Entity Views Attachment (I have not tried the 8 version, but for Drupal 7 it worked nice). You configure it from within views, and then choose to attach it to the node. The node remains editable as every other node.

## New answer

Since EVA is not a good solution. Let's make a block. If you create a view block that lists your users. Place the block below your content block in the blocks configuration and then change the visibility preferences. Just enter the path to your content (`/node/1` or something similar. It is favorable to use the node id, because the URL alias can change more easily.).

A lightweight alternative could be to use the `Global: Rendered entity - Content` display in the views header area. This will allow you to embed the complete node in the view. But in this case you will have access to the node via its regular path and the path of the view, which might be undesirable.
> 3 votes

---
Tags: views, 8
---


# Question
Title: Deleting all Webform Submissions and Content from specific IP
Is there a great way to delete all content and webform submissions from a specific IP address? I'm sure it can be done with MySQL commands, but I'm hoping there's a 'safer' way to do it than manipulating the database by hand.

Thanks!

Drupal 7.50 Commons

# Answer
You could use Views Bulk Operations.

Add `Bulk operations: Content` as a field and check mark `Delete item` under Selected Bulk Operations. Make your view format as Table.

You could try using IP Address manager or User IP Log and hopefully one of these modules will allow you to add IP address as a field to your view.

In your View, under Advanced, you may possibly need to add a relationship of author to your view so you can access user fields (IP Field).
> 2 votes

---
Tags: webforms
---


title: Theming views fields with twig

text:
# Question
Title: Theming views fields with twig
I have a search results view from Search API where I need to use the excerpt that highlights the keywords being searched. In this instance, that prevents me from using a view mode output as the result.

In this instance, I have a view set up to output title, URI, date modified and search excerpt. I have a decent bit of theming to do around the form and results, but I can't seem to figure out how to view both the template suggestions for each view field, or just theme it manually in the given template `views-view--unformatted--search--results.html.twig`.

I also tried `{{ kint(row) }}` and even when viewing on its own page, basically locked up my browser.

So for instance, for the title, I need the markup to be:

`<a href="#" class="search-result__item-title">Foo Exam</a>`

For consistency reasons, I would like to control it from twig templates instead of attempt to do it in the views admin (setting label field etc settings).

# Answer
> 1 votes
You're probably looking for

views-view-fields--\[view-name\]--\[machine-name\].html.twig

views-view-fields--search--results.html.twig

In your view click on your title field and uncheck `Link to the content`.

then your template file

```
<a href="#" class="search-result__item-title">{{ fields.title.content }}</a>

```

Not really sure if you really want `#` as `href`. I think you want to link to content. So add `Path` as a field.

```
<a href="{{ fields.path.content }}" class="search-result__item-title">{{ fields.title.content|striptags }}</a>

```

**Note:** You'll probably want to use `|striptags` if you do not strip the markup from the views UI. Unless you do not mind having `<divs>` wrapping your title text.

then `{{ fields.field_machine_name.content }}` each of the rest of your fields that you want to output.

> **Important**: Make sure TWIG DEBUG is off, as it tends to screw up templates in Views.

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


# Question
Title: How do I add a custom button next to the "Add Content" button?
How can I add a button next to the *\+ Add Content* button on /admin/content, in Drupal 8?

>

# Answer
You have to provide `mymodule.links.action.yml` in your module.

This is an example from core for the *Add content* action button from your question:

*node.links.action.yml*

```
node.add_page:
  route_name: node.add_page
  title: 'Add content'
  appears_on:
    - system.admin_content

```

Reference: Providing module-defined actions
> 5 votes

# Answer
To further the answer above, if you want to theme the button you added from `MODULE.links.action.yml` you need to implement the following hook in you `MODULE.module` file:

```
function MODULE_menu_local_actions_alter(&$local_actions) {
  $local_actions['ROUTE.NAME']['options']['attributes'] = array(
    '#target' => '_blank'
  );
}

```

The above hook will add the attribute `target="_blank"` to the link
> 1 votes

---
Tags: 8
---


# Question
Title: What do I use as URL path in a template file?
I've created a custom theme override for views-view-fields.html.twig to views-view-fields--about-us.html.twig which is a listing of members on a site and the code I've used is as follows:

```
{{ fields.field_photo.content }}
<div class="caption">
  <h4>{{ fields.title.content }}</h4>
  <p class="em">{{ fields.field_job_title.content }}</p>
  <a class="btn btn-primary btn-block" href="{{ path }}">{{ 'Learn More'|t }}</a>
</div>

```

However, when I view the page, the only thing not working is the link to the content. The "Learn More" is supposed to go to each persons full bio, but instead, all that it links to is the current page/view.

Is {{ path }} not the correct code to use as the URL? I've tried numerous other solutions that I thought I found on this site for it but it either doesn't work or breaks my site.

**EDIT 1:**

When I try *No Sssweat*'s answer from below, which I had tried before, I get the following issues:

Extra bit of code is printed below the button like the image below:

And, this is what the code looks like when you hover over the link:

# Answer
In Views, you need to add `Path` as a field, which you probably already have, and you can print it like this:

`{{ fields.path.content }}`

so

```
<a class="btn btn-primary btn-block" href="{{ fields.path.content }}">{{ 'Learn More'|t }}</a>

```
> 3 votes

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


# Question
Title: How to display a confirm box before submitting a form?
On the `node/%/edit` form, when the user clicks the Submit button, I want to show a simple pop-up box with the text "Are you sure you want to save your changes?". When the user clicks `Cancel` (or `No`) then nothing happens. If the user clicks `Ok` (or `Yes`) then the form gets submitted.

I already tried out the A's in the following related Q's:

I also read some other A's that used the Rules module but that is totally overkill.

# Answer
**confirm\_popup.info**

```
name = Confirm Popup
description = Adds a confirm popup when saving all nodes.
package = custom
version = 7.x-1.0
core = 7.x
dependencies[] = jquery_update
dependencies[] = overlay

```

**confirm\_popup.module**

```
<?php

/*
 * Implements hook_form_BASE_FORM_ID_alter()
 */
function confirm_popup_form_node_form_alter(&$form, &$form_state, $form_id) {

  $content_type = $form['#node']->type;
  if ($content_type == 'article') {

    $form['#attached']['js'][] = drupal_get_path('module', 'mymodule') . '/js/confirm-popup.js';
    $form['#attached']['css'][] = drupal_get_path('module', 'mymodule') . '/css/confirm-popup.css';

  }

}

```

**js/confirm-popup.js**

```
(function($) {
Drupal.behaviors.confirmPopUp = {
  attach: function (context, settings) {

    $(document).ready(function() {

      $("#edit-submit").attr("type", "fake");
      $("#edit-submit").attr("id", "fake");

      $(document).on("click", "#fake", function(){
        var box = $("<div class='popup-box'><b>Are you sure you want to save your changes?</b><div class='btns-wrapper'><span class='save-btn'>Save</span><span class='cancel-btn'>Cancel</span></div></div>");

        $("#overlay-content").prepend('<div class="blackbg"></div>').prepend(box);
        $("#overlay-content").addClass('transbg');
        $("#overlay-titlebar").prepend('<div class="blackbg"></div>');
      });

      $(document).on("click", ".save-btn", function(){
        $('#fake').attr("type","submit");
        $('#fake').attr("id","edit-submit");
        $('#edit-submit')[0].click();
      });

      $(document).on("click", ".cancel-btn", function(){
        $(".blackbg").remove();
        $(".popup-box").remove();
      });

    });

  }
};
})(jQuery);

```

**css/confirm\_popup.css**

```
.blackbg {
   height: 100%;
   width: 100%;
   position: absolute;
   overflow: hidden;
   z-index: 10;
   background-color: rgba(0, 0, 0, 0.5);
}
.transbg{
   background-color: rgba(0, 0, 0, 0.0) !important;
}

.popup-box{
  width: 350px;
  height: 120px;
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
  z-index: 20;
  background-color: white;
  padding: 10px;
  font-size: 20px;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  font-family: "Lucida Grande", Verdana, sans-serif;
  line-height: 1.2em;
}

.btns-wrapper{

   position: absolute;
   bottom: 15px;
   text-align: center;
   font-size: 15px;
   display: block;
   margin: auto;

}

.save-btn,
.cancel-btn{
  padding: 10px;
  width: 70px;
  cursor: pointer;
  border-radius: 5px;
  display: inline-block;
}

.save-btn{
  background-color: #6bc711;
  margin-right: 10px;
}

.cancel-btn{
  background-color: red;
}

#fake{
  width: 34px;
}

```

# Result
> 5 votes

---
Tags: 7, forms, javascript
---


# Question
Title: Is it possible to uninstall a module which is causing some errors?
I have installed Views Bulk Operations but it is causing errors since it needs PHP 5.2.9 while my hosting is PHP 5.2.6. I have no option to turn it off, it has a red cross.

How to remove this module?

# Answer
Yes, you can uninstall it, here is the easiest way-

If you have phpmyadmin access then-

You can disable a module via phpMyAdmin by login to phpMyAdmin. Then you must locate the database where Drupal is installed. Once you have done so look for the "system" table. Click and open it. Click to browse the table. Find the record for the module that is causing the problems and select the edit function. Set the status to "0" and save. So this will disable the module, now you can access your site and can easily login to backend and uninstall the module.
> 2 votes

# Answer
Just to add information to Rahul Mishras post, if you don't know which command lines to use to delete the module tables from PhpMyAdmin. Here's how:

1. See all the modules that have been installed enabled or not:

> SELECT name,status FROM system WHERE type='module';

2. See all the modules enabled:

> SELECT name,status FROM system WHERE type='module' AND status='1';

3. See if a particular module is enabled:

> SELECT name,status FROM system WHERE name='module\_name';

4. Disable your module, set the status to 0 for the module name that you want to disable.

> UPDATE system SET status='0' WHERE name='module\_name';

And lastly, clear the cache, just to be sure:

> DELETE FROM cache\_bootstrap WHERE cid='system\_list';
> 2 votes

# Answer
First disable the module by going to `/admin/modules` find Views Bulk Operations and disable by uncheck marking it and click save button.

Now in the top right, click the Uninstall tab, checkmark Views Bulk Operations and click uninstall button.
> 0 votes

---
Tags: 7, views
---


# Question
Title: Commerce product entity not being saved by EMW from another entity form submit
I'm using the module Commerce Stock Sources to manage different stock locations for my products.

When saving the Commerce stock sources form, on form submit, I want to update a field value on the Commerce product entity. The field is an Entity reference field.

The problem is that I can't get the field updated. No notice or error returning.

```
    //first I'm getting the values to be set; will have a simple array of IDs
    if (!empty($form_state['values']['plugins']['plugin_settings'])){
                $selected_sources = array_values(array_filter($form_state['values']['plugins']['plugin_settings']));
        }
    //next I'm loading the product entity; I have checked, the product is loading OK
    //and then the wrapper and the operations
    $product_entity = entity_load_single('commerce_product', $form_state['complete form']['#product']->product_id);
    $wrapper_product = entity_metadata_wrapper('commerce_product', $product_entity);
    if (!empty($selected_sources)) {
        $wrapper_product->field_product_location_store = $selected_sources;
        $wrapper_product->save();
    }

```

The field is not updated. I've checked to see if I can read values from product using `entity_metadata_wrapper()` and it works. When I try to update any field, it doesn't work.

I tried updating with `field_attach_update()`, but it doesn't work either.

```
        for($i=0; $i<count($selected_sources); $i++){
          $product_entity->field_product_location_store[LANGUAGE_NONE][$i]['target_id'] = $selected_sources[$i];
        }
        field_attach_update('commerce_product', $product_entity);
        entity_get_controller('commerce_product')->resetCache(array($product_entity->product_id));

```

Any thoughts?

# Answer
It's seems that by using the product entity directly from `$form_state['complete form']['#product'];` the `entity_metadata_wrapper()` works as expected and it saves the values.

```
if (!empty($form_state['values']['plugins']['plugin_settings'])){
    $selected_sources = array_values(array_filter($form_state['values']['plugins']['plugin_settings']));
}
    //get directly the product, without entity_load_single()
    $product_entity = $form_state['complete form']['#product'];
    $wrapper_product = entity_metadata_wrapper('commerce_product', $product_entity);
    if (!empty($selected_sources)) {
        $wrapper_product->field_product_location_store = $selected_sources;
        $wrapper_product->save();
    }

```

Although the object loaded by `entity_load_single()` is identical with the object obtained by `$product_entity = $form_state['complete form']['#product'];` the `entity_metadata_wrapper()` works only for the second case, which seems more logical and is faster.
> 0 votes

---
Tags: 7, commerce, entities
---


# Question
Title: How to determine if a script is started by cron?
I have a script that run in some cases when some event occur. It also run when cron run (cron.php) or the "Run cron button" from admin panel is clicked.

How can I determine that from script that is started by drupal cron.php?

# Answer
> 1 votes
You may check your $\_SERVER globals in the script.

A better way, I think, would be to pass a parameter with your call to the script that separates the caller (I.e when you call it from the HOOK\_cron(), add a myFunc(..., $caller="cron") to your call. And declare myFunc(..., $caller=null) as default parameter.

If this is not possible, you may set a session variable in HOOK\_cron and check that in your script.

# Answer
> 1 votes
If you want to run a script during cron, you should do so by invoking `hook_cron` in a module like this:

```
function my_module_cron() {
  invoke_custom_script();
}

```

When you do this, you could tell the script, that it is being called from cron by adding a parameter etc. This could be done like this.

```
function my_module_cron() {
  invoke_custom_script(array('context' => 'cron'));
}

```

---
Tags: 7, cron
---


# Question
Title: "Really" disable entire cache during development (also routing, twig templates, css+js libraries)
I have followed the community documentation page at https://www.drupal.org/node/2598914 (Disable Drupal 8 caching during development). Now I expect that the caching in my Drupal 8 site is entirely switched off. However, for setting up an new route, a twig template or any css/js library in mymodule/mymodule.libraries.yml, I still need to run

```
drush cr

```

to get my stuff recognized by Drupal 8. How can I "fully" disable caching? It is annoying to run "drush cr" dozens of times and repeatedly guess if the specific item is either cached or not..

# Answer
> 1 votes
I asked this on twitter and @renebakx replied:

> @stevepurkiss check how devel modules handles this, it worked for templates and added css/js to the theme's library. Not for added routes

---
Tags: 8, caching
---


title: Two relationships in Views

text:
# Question
Title: Two relationships in Views
I'm wondering if the following construction is posible with Views in Drupal in combination with relationships. I build this in Drupal:

```
Manager <--(Entity Reference)--> Group <--(Entity Reference)--> User

```

A manager can control groups with different users, so I have the following setup:

> Manager A \<--\> Group A \<--\> User 1
> Manager A \<--\> Group A \<--\> User 3
> Manager A \<--\> Group A \<--\> User 5
> Manager B \<--\> Group B \<--\> User 2
> Manager B \<--\> Group C \<--\> User 4
> Manager B \<--\> Group C \<--\> User 6
> Manager B \<--\> Group C \<--\> User 7

I'm looking for a way to generate a view with the logged in manager to get all the users of the group the manager is part of.

So we get this result when I'm logged in with manager B:

> User 2
> User 4
> User 6
> User 7

I tried to create an Contextual filters with an default value of the logged in user. Then 2 relations: one for the

```
Manager <--(Entity Reference)--> Group

```

ans an second one for the

```
Group <--(Entity Reference)--> User

```

And then I tried to make fields with an relationship. But only I get is no results. Is there a way to get this working?

# Answer
You will want you view set up so that:

* The view is displaying Users.
* There is a relationship from User to Group
* There is a relationship from Group to Manager
* You add the contextual filter that defaults to the currently logged in user. Make this filter use the Group-Manager relationship.
> 1 votes

---
Tags: views
---


# Question
Title: How to resolve the SMTP not connect to server drupal?
I have used the SMTP Module for sending mails and done all the configuration according to this link(URL: http://www.symphonythemes.com/drupal-blog/configure-drupal-smtp-gmail).

But I could not send a mail. The error is like phpmailerException: SMTP Error: Could not authenticate. in PHPMailer-\>SmtpConnect().

Please help me, How to sort out this issue.

# Answer
> 3 votes
If you are using gmail account for SMTP then you need to enable "Allow less secure apps: ON" under "sign-in & security" of you google account settings.

---
Tags: 7
---


# Question
Title: Creating a block to show content in the same group of the current node
I would like to create a block that in `node/x` displays the links to all the nodes in the same group as x. I created a view of Content, a relation of Group but no contextual filter allows me to filter by current node's parent group

# Answer
Add contextual filter "Content: Has taxonomy term ID" and make configuration like below

1. Provide default value : Taxonomy term Id from URL
2. Load default filter from node page, that's good for related taxonomy blocks
> 0 votes

---
Tags: views, 8, group
---


# Question
Title: ERR_TOO_MANY_REDIRECTS on images after switch to HTTPS
I have the Drupal 8 site was working with HTTP on the port 80. I switched it to HTTPS with port 443. I got the problem for ERR\_TOO\_MANY\_REDIRECTS when accessing some images from physicals path.

For example path: https://www.example.com/theme/sites/basic/img/fileimage.png

It happened on some files which are display on the pages. I tried access other files on the same level folder "img" is working. (i.e img/logo.png)

I guess it's cache problem. Here what I did: \- Clear cache \- Drush cr \- Deleted some special table within cache\_ inside. \- I stop mysqld, it's still happened.

Here is my .htaccess:

```
# ensure www.
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# ensure https
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

```

From my admin/config/Basic Site Setting. I still saw

```
Default front page: http://www.example.com

```

It should be https? How I can resolve it? Thanks

# Answer
On Drupal 8 I fixed it by change

```
RewriteRule ^ - [E=protossl]
RewriteCond %{HTTPS} on
RewriteRule ^ - [E=protossl:s]

```

to

```
# if you enable "www." stripping or enforcement, in order to ensure that
# you don't bounce between http and https.
RewriteRule ^ - [E=protossl]
RewriteCond %{HTTPS} off
RewriteRule ^ - [E=protossl:s]

```
> 0 votes

# Answer
**Try this out** -

```
# ensure www.
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^ https://www.example.com%{REQUEST_URI} [L,R=301]

# ensure https
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [L,R=301]

```
> 0 votes

---
Tags: 8, redirection, .htaccess, ssl
---


title: Custom attribute in views fields

text:
# Question
Title: Custom attribute in views fields
I am trying to add custom attribute with elements like "data-url" and "data-text" in views fields, it shows something like "data-text="test text"\> as output on front end. How can i add them so that they work as attribute and not print as text ?

# Answer
> 1 votes
It's not initially obvious where and how to make these changes, fortunately it's not too hard to rewrite the output of the fields in views.

You can make a new views template fields from the display:

*`Other > Theme:Information link`*

Then edit the code adding your HTML around the Php and dropping it into your theme templates folder.

Or another way which I find is a lot quicker especially when there is a lot of changes going on in a development of a site, use the global custom text field or write the content fields.

I will use the title field to add an attribute as an example for you to follow.

In your view:

```
*edit Fields > title*

*Rewrite results >* tick *Rewrite the output of this field*

```

In the text field add the following code using the tokens options provided and editing your HTML to your requirements.

```
<h2 class"yourclass" data-text="test text">[title]</h2>

```

Save the view and you will see your attributes in your Views display.

To add to this if you use the field Global text you can hide each of your fields then rewrite the HTML to whatever you need to, adding HTML for each token in the row.

---
Tags: 7, views, entities
---


# Question
Title: View menu routes missing until first page load
I having an issue with the installation logic of a custom module. I am trying to add menu links using `menu_link_save()` that link to a view that is defined in my module in `hook_views_default_views()`.

I am creating a new site using a installation profile that installs this custom module by default. I'm not sure if this is related to being in the install/update environment instead of the normal page environment.

The problem I am having is that the view hasn't created any route in the menu\_router table. When I add a link I get a row in menu\_links, but the router\_path column is empty and the row gets deleted by Drupal when it decides to rebuild the menus.

Is there way to cause the view to populate the menu\_router table so that I can add links normally? Is there another way I can use for this? I would like to be able to keep my profile and, rely on a single site install action instead of having to do something after installing, as follow up.

The link never appears; Drupal deletes it from the menu\_links table.

# Answer
> 0 votes
## Problem background

I actually found an answer to this problem. Drupal has a rather aggressive way of deleting menu items that has the `router_path` field set to `NULL` (or empty) in table `menu_links`. If Drupal finds such a record it will delete the record upon the next run of `menu_rebuild();` (see docs) or documentation block below.

```
/**
 * Populates the database tables used by various menu functions.
 *
 * This function will clear and populate the {menu_router} table, add entries
 * to {menu_links} for new router items, and then remove stale items from
 * {menu_links}. If called from update.php or install.php, it will also
 * schedule a call to itself on the first real page load from
 * menu_execute_active_handler(), because the maintenance page environment
 * is different and leaves stale data in the menu tables.
 *
 * @return
 *   TRUE if the menu was rebuilt, FALSE if another thread was rebuilding
 *   in parallel and the current thread just waited for completion.
 */

```

## Solution

Each menu item created this way must contain the property `customized` and have its value set to to `1`. This forces Drupal to update the record in table `menu_links` with the matching `router_path` instead of deleting it. See function `_menu_navigation_links_rebuild($menu)` around line 2929 in `menu.inc`. `_menu_navigation_links_rebuild($menu)` is called from `menu_rebuild()`.

### Example

This will create a new link on the top level in a menu named 'your-menu-name'.

```
$ls = array(
  'menu_name' => 'your-menu-name',
  'link_title' => 'Your Link Title,
  'link_path' => 'your/link/path',
  'plid' => 0,
  'weight' => 0,
  'customized' => 1, // "The magic property"
);

$newpid = menu_link_save($ls);

```

---
Tags: 7, views, routes
---


title: Exporting fields for content type

text:
# Question
Title: Exporting fields for content type
The configuration export feature of Drupal 8 would seem to be a very useful feature. However, I'm not sure I completely understand how it works.

For example, if I do a single export, choose "Content type" then select one of my content types, I would expect that export to contain a full description of that content type. But it doesn't contain any information about the fields in that content type. So if you wanted to export a content type configuration for use on another site, it doesn't seem possible to do that.

I'm not sure I understand the use of being to do Single exports if they don't contain all the required data for an entity. Am I missing something?

# Answer
**UPDATE**

You might also try Drupal Console's `drupal config:export:content:type` command.

It's description says:

> The config:export:content:type command Export a specific content type and their fields.

---

Content types and Fields are 2 separate configuration in Drupal 8, so if you want to export content type with fields you have to export all it's fields configurations too.

Features module might be helpful for grouping configurations, it's not stable yet, I haven't tried it but I think it might worth trying.
> 10 votes

# Answer
I've written a Python script (below) which exports **a group of configuration items** using `drush`. It may be useful in your case (it has been in my case). Usage:

`export_config_group.py -s something -m foobar`

This executes `drush config-list`, gets all the items whose name contains the term `something`, then saves them to `modules/custom/foobar/config/install`.

The script also adjusts the yml as follows:

* removes the `default_config_hash` entry when it exists;
* removes the `uuid` entry when it exists.

The script depends on ruamel.yaml to load and dump the configuration. Make sure you `pip install` it in advance.

```
import os
import argparse
import subprocess
import ruamel.yaml

MODULES_ROOT = "/var/www/html/dm/web/modules/custom"

def main():
    search_term, module, keep_uuid = parse_arguments()
    module_config_path = os.path.join(MODULES_ROOT, module, 'config/install')
    items = run_process(['drush', 'config-list']).splitlines()

    for item in items:
        if search_term in item:
            print "Config item:", item

            yml = run_process(['drush', 'config-get', item])
            new_yml = adjust_yml(yml, keep_uuid)
            full_path = os.path.join(module_config_path, item + '.yml')

            with open(full_path, 'w') as f:
                f.write(new_yml)

def parse_arguments():
    ap = argparse.ArgumentParser(description="Export config group.")
    ap.add_argument("-s", "--search", required=True, help="Search term")
    ap.add_argument("-m", "--module", required=True, help="Destination module")
    ap.add_argument("-u", "--uuid", help="Keep UUID",
                    action='store_true', default=False)
    args = ap.parse_args()
    return args.search, args.module, args.uuid

def run_process(params):
    process = subprocess.Popen(params, stdout=subprocess.PIPE)
    stdout, _ = process.communicate()
    return stdout

def adjust_yml(yml, keep_uuid):
    loader = ruamel.yaml.RoundTripLoader
    config = ruamel.yaml.load(yml, loader, preserve_quotes=True)

    remove_core_config_hash(config)

    if not keep_uuid:
        remove_uuid(config)

    dumper = Dumper = ruamel.yaml.RoundTripDumper
    return ruamel.yaml.dump(config, Dumper=dumper, indent=2, block_seq_indent=2)

def remove_core_config_hash(config):
    if '_core' in config:
        if 'default_config_hash' in config['_core']:
            config['_core'].pop('default_config_hash')

            # Also remove '_core' node if empty
            if not config['_core']:
                config.pop('_core')

def remove_uuid(config):
    if 'uuid' in config:
        config.pop('uuid')

if __name__ == "__main__":
    main()

```
> 0 votes

---
Tags: 8, importing-exporting, configuration
---


title: resave all taxonomy terms by vbo

text:
# Question
Title: resave all taxonomy terms by vbo
I have a site with a large number of taxonomy terms. Now I need to add meta keywords and meta description to all of this terms. My solution is :

1. Resave all terms by VBO module.
2. Create a rules on "before saving taxonomy term".
3. The created rules execute a PHP code which adds meta keywords and meta description to each of the tags.

In this way when VBO is resaving terms one by one my rules is executed for each of theme and do the trick.

Now the problem is in step one. I have an "execute arbitrary PHP script" operation in VBO for terms. I use this code in it:

```
taxonomy_term_save($entity);

```

but I face this error:

> An AJAX HTTP error occurred. HTTP Result Code: 200 Debugging information follows. Path: /backup-sar/batch?id=412&op=do StatusText: OK ResponseText: Fatal error: Function name must be a string in C:\xampp\htdocs\backup-sar\sites\all\modules\views\_bulk\_operations\actions\script.action.inc(20) : eval()'d code on line 1

This one with the same error does not work too:

```
taxonomy_term_load($entity->tid);
taxonomy_term_save($entity);

```

Any help would be appreciated. Thanks in advance.

# Answer
> 0 votes
If you're executing the VBO operation while in the Views configuration page, you're likely to run into this error. Save your view and go to the URL for that view and then run the operation.

A 200 return code actually indicates success, but the presence of the AJAX debugging screen interferes with the completion of the operation.

I know because I just ran into a nearly identical issue. :-)

---
Tags: taxonomy-terms, rules, views
---


# Question
Title: Send mail to email addresses from webform when a content is saved
I want exactly like this Send notification e-mail after new content was added but the answer is not seems to be question specific. I have a webform where I get email id of the anonymous users and I want to send email to those ids when I save a new content.

I have combined Rules and webform rules for it. I created an

**event** -*After saving new content*

**Condition** -*Content is of type*

**Actions** -*Fetch webform submissions of node ID n*

**Loop** -*fetched submissions*

**loop action** -*Send mail*.

But i am stuck to move forward as I am not able to configure 'TO' field with email fields from fetched submissions.

# Answer
Enabled the PHP filter module and the list item is available in the PHP evaluation area. So fetch the email is as `<?php print $list_item->data['component_id']['value'][0]; ?>`. Works pretty well :)
> 1 votes

# Answer
I don't think you have to "***Enabled the PHP filter***" (as in your own answer) to get this to work. Read on for an alternative solution ...

You do have access to all ***labels*** and all ***values*** of any field of a webform, ie:

* `[data:MachineFieldName-title]` contains the **Label** of a field with machine name MachineFieldName.
* `[data:MachineFieldName-value]` contains the **Value** of a field with machine name MachineFieldName

So in your case, you should be able to get it to work using something like `[data:email-id]` (assuming that's what corresponds to the "*email id of the anonymous users*" in your case).

For way more details on this, and a prototype rule about this, refer to the answer to "How to create a node from a Webform using rules?":

* the *1st attempt* relates to using "Entity has field" (which doesn't work for Webform)
* the *2nd attempt* explains what to do in case of Webform.
> 0 votes

---
Tags: rules, webforms
---


# Question
Title: Drupal 8 does not create path alias' valid for all languages
I have a Drupal 8 multi lingual site setup using the module Pathauto to generate path alias for taxonomy terms. The alias are created form the name of the tags, which are not translated but rather are in all languages the same. So I want all those alias be valid for all languages. The settings page of the module Pathauto lets me either leaving all languages unselected or choose specific languages for which the created path should be valid for. But unfortunately the pathes are created only for English and do not work if a user has a different language selected.

Is that a bug, or am I not doing it correctly?

# Answer
That's currently not supported.

Partially blocked by core, which also doesn't allow to create language-neutral aliases while editing nodes and then also wouldn't show them anymore. See https://www.drupal.org/node/2511968 and https://www.drupal.org/node/2689459. Once those are resolved, pathauto could follow those definitions.
> 3 votes

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


title: Add field 'link' in a block form?

text:
# Question
Title: Add field 'link' in a block form?
I would like to had a field link in a custom block. Here is my code to do that :

public function blockForm($form, FormStateInterface $form\_state) {

```
$form['key_1'] = [
    '#title' => $this->t('Key 1 label'),
    '#type' => 'textfield',
    '#default_value' => '',
    '#required' => false,
];

$form['key_2'] = [
    '#title' => $this->t('key 2 link'),
    '#type' => 'link',
];

return $form;

```

} Now, when I go in admin/structure/block/manage/myblock, I can see my key 1 field. The key 2 is not render. If I change the type for any other (textfield, textarea, file\_managed) my field is properly render. The default link module is enabled.

Is the link field type only usable in node form ? I can understand why.

# Answer
> 3 votes
You should add the field from the Block Type interface. Either add to the block type that comes with core or create a new one and add your fields.

Also, no, Drupal Fields and Form API elements are two different constructs. That is why 'link' does nothing. It would simply be:

```
$form['key_2'] = [
    '#title' => $this->t('key 2 link'),
    '#type' => 'url',
];

```

See: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21Element%21Url.php/class/Url/8.2.x

But you're creating more work that necessary.

In this context (a form) `link` pertains to a RenderElement and not a FormElement like `url` is.

---
Tags: 8, forms, blocks
---


# Question
Title: How to translate strings in (programmatically created) custom module?
I've (programmatically) created a custom module which includes a block with a string wrapped in the $this-\>t() function. How or where can I extract this translation file?

In Drupal 7 I would extract a translation file of the custom module, but the POTX module is not ported to Drupal 8 yet.

```
public function build() {
  return array(
    '#markup' => $this->t('How and where can I translate this string?'),
  );
}

```

# Answer
Potx is not yet ported to Drupal 8 but it can parse Drupal 8 modules.

You can install it as a drush command instead of a drupal module and then it should work fine on your Drupal 8 module.

What that doesn't support yet is extracing existing translations from a running site. Looks like people are working on a port in https://www.drupal.org/node/2356469 which supports that.
> 1 votes

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


# Question
Title: How do I access the values of my results from a view
I have a preprocess function that I would like to run against a view, but I can not seem to be able to access the actual results. I have a custom entity called entity1 with two fields, field1 and field2. This function runs, but the value of $value is never set

```
function template_preprocess_views_view_hook(&$variables) {
  // View options set by user.

  foreach ($variables['view']->result as $id => $result) {
    //Things I've tried:
    $value1 = $result->field_field_field1;
    $value2 = $result->field_field_field1[0]['raw']['value'];
    $value3 = $result->entity1_field_field1;
    $value4 = $result->field1;
    //and many other things
  }
}

```

The foreach loop does in fact cycle through for the correct number of results.

# Answer
You need the method getValue() from each `field` to get the field data from `row`:

```
$view = $variables['view'];
$values = [];
foreach ($view->result as $row_id => $row) {
  foreach ($view->field as $field_id => $field ) {
    $values[$row_id][$field_id] = $field->getValue($row);
  }
}

```

If you want the rendered field use `$field->render($row)`
> 1 votes

---
Tags: views, 8
---


# Question
Title: Route AJAX failure messages to console instead of popup
How can I prevent ajax failure popups and instead route the failure to the console log instead? Is this something I can do with Drupals implementation of jQuery?

# Answer
> 4 votes
You can check Prevent JS alerts module..

Project page says

> This module is an answer to the issue: #1232416: Drupal alerts "An AJAX HTTP request terminated abnormally" during normal site operation, confusing site visitors/editors, which describes a big problem for end users: JavaScript alert();'s for end users on AJAX errors by Drupal core. Perhaps it will one day become obsolete, when this bug is fixed. End users are often frightened of these errors and don't know, if they have "destroyed the internet" ;)
>
> This module completely suppresses ALL JavaScript alerts and instead prints them to console via console.error! Important: It does NOT ONLY suppress the core alerts, but also custom alerts.

# Answer
> 1 votes
The prevent\_js\_alerts module is a heavy handed approach to handling ajax errors. If you want to intercept some errors, you can try something like this in your module or theme, which gives you a way of conditionally intercepting some messages, and letting Drupal do the default for everything else.

```
(function ($) {

  Drupal.behaviors.catchSomeDrupalAjaxAlerts = {

    attach: function(context, settings) {

      // Replace this simple core function with one that won't blurt empty messages.
      Drupal.displayAjaxError = function (message) {
        if (message && !Drupal.beforeUnloadCalled) {
          alert(message);
        }
      }

      // Intercept ajaxError to handle certain messages.
      Drupal.ajaxErrorDefault = Drupal.ajaxError;
      Drupal.ajaxError = function (xmlhttp, uri, customMessage) {
        var message = '';
        try {
          message = xmlhttp.error.message;
        }
        catch (e) {}

        // Handle various known cases.
        if (uri.indexOf('file/ajax') !== -1 && message == 'Unexpected end of JSON input') {
          // DO SOMETHING ELSE HERE
          $('body').append('<div class="error">SOMETHING HAPPENED PLEASE CONTACT 911</div>');
          return false;
        }
        else {
          // Passthru to the default Drupal.ajaxError if we don't want to intercept it.
          return Drupal.ajaxErrorDefault(xmlhttp, uri, customMessage);
        }
      }
    }
  };

})(jQuery);

```

This code is a variation of some project code, and may not work without some debugging. This solution is also similar to the module ajax\_error\_behavior.

---
Tags: 7, ajax, javascript
---


# Question
Title: How to show fivestar votes in views as number instead of percentage?
I have a view which show a content with a Fivestar field (votes). The problem is that the field is shown as the percentage of votes, not like the stars, or the number (in fact I need to show the number instead of percentage).

I mean, my Fivestar field has 10 stars. Well then if, for example, a node has 7 stars, rather than see the 7 stars or the number of stars (7) is shown the percentage, 70.

What I have to do to show the number (in my example "7")?

# Answer
> 1 votes
I found a solution for my question: Hide your vote field in views ("Exclude from display"); then, add a Global field, the "global math expression", and in this field add a replacement token of your exclude field, in my case `[value]`. Finally add the mathematical expression to divide by 10 the number: `[value]/10`. Apply and save the view.

---
Tags: 7, views, rating
---


# Question
Title: How to disallow flags to get triggered if one of the user fields is empty?
I have a user flag "Status" and I have some fields for that user like name, phone etc.

How do I not let moderators trigger that flag if any of that user field is empty?

# Answer
Use the Rules module to implement what you're asking for, as detailed in the blueprint below ...

### Step 1: Create a custom rule

Create a rule like so:

* Event: after updating an account.
* Conditions:
    + user does not yet have role (say) "abc".
    + check that none of those user fields are empty.
* Action: grant access to a role (say) "abc".

For an example of a rule (in Rules export format) that is pretty close to what you need, have a look at my answer to "How to implement admin verification for selected user profile fields?".

### Step 2: Tune the configuration of the flag

Adapt the configuration of your "Status" flag, so that you only authorize it to be used by ... euh ... indeed, users who have access to role "abc".

Happy flagging with Rules!
> 1 votes

---
Tags: 7, users, flags
---


# Question
Title: Why some functionality of my drupal site is different on different PCs?
I created a site but when I log in from another PC (exact same site), some things are different. Like on my laptop, my ajax loader is working beautifully but it lags on my office computer. There is a message on successful image update (from media module) on my PC but there is no message in my laptop (however that should be the case).

What's happening here? I'm lost.

**UPDATE**

I saw a JavaScript error on my PC which is very much different than the JS error on my laptop. They are the same file, same webroot and same website. Even after turning off my development environment, I am not going further.

**UPDATE**

Problem Solved, the origin of the issue was JQuery Conflict. After defining different reference variables, my problem is free. Although I still don't understand why this was not a problem in my machine. Is there a mechanism that I'm missing?

# Answer
The origin of the issue was Jquery Conflict. After defining different reference variables, my problem is free.
> 1 votes

---
Tags: 7
---


# Question
Title: What is the correct way to document the schema for a YAML file?
As a module developer, I'd like to convert some of my Drupal 7 info hooks to YAML discoveries in Drupal 8, but it's not clear to me how to document the schema of a YAML file for consumers. For a hook, of course, I would define `hook_whatever()` in `mymodule.api.php`. What do I do for `*.whatever.yml`? What is core doing?

# Answer
> 1 votes
There is no "documenting" of hooks in D8 except the mymodule.api.php as you've already mentioned(+ impleneting hook\_hook\_info).

The YAML files are only for:

* services
* routes
* menu local tasks
* menu local actions
* libraries
* module info
* simple configuration
* simple configuration schema

Now you've mentioned "info" hooks. In Drupal 8 these are Annotations and their implementations are Plugins. If this is assumption correct then see the documentation in here https://drupal.org/developing/api/8/plugins for plugins - what they are, how they work and how to use them.

# Answer
> 1 votes
The closest thing I could find to documentation of what you can and cannot put in the YAML files, are the \*.schema.yml files in core. For example, when you create a new content type, the available keys for your `node.type.my_content_type.yml` file is specified in `/core/modules/node/config/schema`:

```
node.type.*:
  type: config_entity
  label: 'Content type'
  mapping:
    name:
      type: label
      label: 'Name'
    type:
      type: string
      label: 'Machine-readable name'
    description:
      type: text
      label: 'Description'
    help:
      type: text
      label: 'Explanation or submission guidelines'
    new_revision:
      type: boolean
      label: 'Whether a new revision should be created by default'
    preview_mode:
      type: integer
      label: 'Preview before submitting'
    display_submitted:
      type: boolean
      label: 'Display setting for author and date Submitted by post information'

```

This means, you may specify `name`, `type`, `description`, `help`, `new_revision`, `preview_mode` and `display_submitted`. My guess is that other keys will be ignored.

This answer needs community input, since there is still a lot of uncertainty.

# Answer
> 0 votes
* Create a folder named mymodule inside sites/all/modules or modules
* Create mymodule.info.yml and mymodule.module files insides your module "mymodule" folder

Code for mymodule.info.yml goes below

```
name: My Module
description: 'My Module description.'
package: Custom
type: module
version: 1.0
core: 8.x

```

If you want to invoke a hook you need to use something like below on some event function..

```
  \Drupal::moduleHandler()->invokeAll('whateven', array($args));

```

For Example.. User.module does this for user logout event

```
/**
 * Logs the current user out.
 */
function user_logout() {
  $user = \Drupal::currentUser();

  watchdog('user', 'Session closed for %name.', array('%name' => $user->getUsername()));

  \Drupal::moduleHandler()->invokeAll('user_logout', array($user));

  // Destroy the current session, and reset $user to the anonymous user.
  session_destroy();
}

```

Regarding api.php files.. They are just used for documentation purposes to help developers..

Regarding .info.yml files they are required to:

* Notify Drupal about the existence of a module, theme or install profile.
* Provide information for the Drupal Web UI administration pages.
* Provide criteria to control module activation and deactivation and Drupal version compatibility.
* General administrative purposes in other contexts.

Implementing a hook is still same in Drupal 8 .. Defining a function with module name followed by hook name.

---
Tags: 8
---


title: Download attached files in a Zip

text:
# Question
Title: Download attached files in a Zip
Im doing a website for photos. The photographer uploads all the images and drupal generates a thumbnail and a resized image.

What i'm trying to do is to put a link , so the final user can download all the original files in a zip files.

Can you guys help me out?

# Answer
> 3 votes
Yes, there's a module for that (of course ;) )

Download module:

> This module can compress any files attached to a node and provides a download link. To use this module you have to extract the PclZip library in /sites/all/libraries/pclzip which can be downloaded here: http://www.phpconcept.net/pclzip/pclzip-downloads.

# Answer
> 0 votes
There's a better suited module available for that functionality now: ~~https://www.drupal.org/project/zipcart, put everything into a cart and download a zip. About to start using zipcart for a project myself~~

Edit: ended up with DocBinder because zipcart got abandoned.

# Answer
> 0 votes
PHP has a ZipArchive class.

I'm writing some code at the moment to implement this in Drupal on a node save. I'll add an example later. But for now there are examples on the ZipArchive page.

---
Tags: views, files
---


# Question
Title: How can I programatically change the color of node title in views results?
I want to change the color of the node titles from a view (fields on table). My first ides was to alter the title and add a span with inline css.

```
function views_titles_views_pre_render(&$view) {
if ($view->name == 'documents' && $view->current_display == 'page') {
    $span_open  = '<span style="color: green !important;">';
    $span_close = '</span>';
    $view->style_plugin->render_fields($view->result);
    foreach ($view->style_plugin->rendered_fields as $index => &$rendered_result) {
      // Add HTML markup icon on rendered title field
      $rendered_result['title'] = $span_open . $rendered_result['title'].$span_close;
    }
  }
}

```

Although my attempt was a success, I managed to alter the title the css rule did not alter the color of the a tag. I figured out that I should go deeper into the title. As far I can tel the dpm of the views\_pre\_render does not show more options.

I have experience with drupal site building, but I am not in any way a php developer.

Can someone help me figure this out?

ps: I know there other more easy ways to achieve that but I want to do it with a module.

# Answer
An easier (and more maintainable) way to achieve this would be to set a class in your span, instead of hardcoding the style. Something like the following:

```
$span_open = '<span class="my-title">"';

```

You can then add a CSS file to your module, so that you can better specify the color, also overriding the `a` tag. For instance:

```
.my-title, .my-title a {
  color: green;
}

```

For more details about adding CSS to your module, see https://api.drupal.org/api/drupal/includes!common.inc/function/drupal\_add\_css/7.x
> 1 votes

---
Tags: 7
---


# Question
Title: How to set value after the page redirecting?
My scenario is set Taxonomy value after the page redirected.

```
if(($weight === "Above 90") && ($height === 'Above 7.0"')) {
    $form_state['redirect'] = $base_path . '/example/other/redirect-1';
    $term = taxonomy_term_load('371');
    // echo '<pre>'; print_r($term->description); die;
    print render($term->description);
 }

```

Here, Once the condition is satisfied, its redirecting to the (/example/other/redirect-1)page. But, the Taxonomy value is not displaying in this page.

I am not sure, whether I am doing in a right way, or Please guide me to solve this issue ?

# Answer
You need to pass the `term_id` along with the `$form_state['redirect']` like
`$form_state['redirect'] = $base_path . '/example/other/redirect-1/?tid='.$term_id;` and get the `term_id` in `/example/other/redirect-1/` page
write something like below

```
 $term_id = $_GET['tid'];
 $term = taxonomy_term_load($term_id);
 print render($term->description);

```

I am giving you an idea some modification may need on code. You need to check.
> 1 votes

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


# Question
Title: How to embed edit user profile page in a panel
I am trying to embed the edit user profile page (ie what appears at the url domain.com/user/27/edit) into a panel. I have searched high and low on how to do this but I can't find any info on it. Is it possible to do this? There reason why I am asking is that I want to clean up the user's profile page so that it looks more professional and is easier to use.

Can anyone point me in the right direction on how to accomplish this?

Thanks

# Answer
> 0 votes
You need 1 context and 1 relationship to get the Form pane

Context: User =\> current user

Relationship: User category edit form from user (default?)

and THEN you get the "Forms" category with "General form pane" under it

---
Tags: 6, panels, users
---


# Question
Title: How to display multiple PDF files in a node
I want to display multiple pdf files in a single node. I am using PDF module to display pdf files with File Resumable Upload. But I need to display many files in a single node. I wasnt able to find any solution to this. When I select multiple files to upload, all get uploaded successfully in the uploads directory, but only one gets displayed. When I go to 'Edit' tab on the same newly created node, all the pdf files are present in the designated section , but only one is displayed on the node (even after saving again).

# Answer
Check maybe the Field Settings (/admin/structure/types/manage/page/fields/...) of your page if the displayed "Number of values" is set to "Unlimited" instead of 1.
> 0 votes

---
Tags: nodes, files
---


# Question
Title: How to display panes/views/blocks based on time of day and day of week?
Building a D7 site, I need to be able to automatically enable/disable Panel panes and/or views (or in the worst case scenario blocks) based on the time of day - different contact info for out-of-office hours and some other stuff. I also need to display drastically different sets of panes and views on the frontpage based on the day of week.

My temporary solution is to set up a number of Panels pages (for changing panes/views) and duplicate themes (for changing blocks) and run cronjobs with Drush's variable-set to change frontpage from one Panel page to another and to change theme to the one with different blocks enabled.

As simple as the above is, it's a terrible long-term solution because all other, unrelated changes made to the site then often require being made more than once and it's really hard to keep track of.

So is there a more straightforward way to configure per-pane, per-view or per-block setting to get enabled/disabled based on time of day / day of week?

# Answer
> 2 votes
Oddly enough, it doesn't look like any of the **Date** modules integrate with ctools for selection rules.

I think you have two options, that are essentially the same thing.

* Panel page variants support **PHP code** selection rules.
* Panels panes support **PHP code** visibility rules.

So, your page(s) could have variants based on date/time, and each variant could have panes that are only visible based on date/time.

Your PHP selection rules will use `time` and/or `date`. For example, this should set a rule to only select or be visible on Monday.

```
$now = time();
$day = date("D", $now);
return $day == "Mon";

```

The `date` function does default to the current time, but explicitly using a `$now` parameter can prevent problems when you call `date` multiple times when you cross midnight.

# Answer
> 0 votes
If you're willing to use the "Rules" module, then you should be able to also get this to work for your "*worst case scenario blocks*" (as in your question). Provided you can express your actual "logic" (about the actual time-frames?) in appropriate Rules logic.

More details about doing so are explained below.

# Part 1: Rules block visibility

Have a look at the Rules block visibility module. Here is a quote from its project page:

> The Rules block visibility module allows Rules components to be used to control block visibility. This provides Drupal administrators and developers extreme flexibility in controlling when blocks should be displayed on their websites, in addition to the default visibility options provided by Drupal.
>
> The general idea is that if you can do it with Rules, you can use it to control block visibility, so the possibilities are limitless:
>
> * Need to show a block only for users registered more than a month ago?
> * Perhaps you have a block that must be shown only between 8am-5pm on weekdays?
> * What about displaying or hiding a block based on current weather conditions?
>
> All of this can be done by using Rules block visibility.

With that, and as per the "*if you can do it with Rules, you can use it to control block visibility*" above, you've reduced your question to making Rules implement the "actual time-frames" logic you asked about.

# Part 2: Create an appropriate Rules Component

The Rules block visibility module doesn't have a lot of documentation, except in the README.txt that comes with this module. Here is what the crucial part of it is (to get the idea):

> Configuration is done on a per-block basis. To control a block visibility using a rule component, go to the block settings page, scroll down to the "Rules" tab, and select the Rules component that you want to use.
>
> Notice that to be able to be used by this module, a Rules component *must* be constructed in a very specific way. See the next section for more information.

This module comes with 2 sample Rules Components, that should help to understand the concept behind it.

By looking at these samples, I was able to create another Rules Component which looks like so:

```
{ "rules_block_visibility_hide_blocks" : {
    "LABEL" : "Hide blocks",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "module" : { "label" : "Module", "type" : "text" },
      "delta" : { "label" : "Delta", "type" : "text" },
      "result" : { "label" : "Result", "type" : "boolean", "parameter" : false }
    },
    "IF" : [
      { "data_is" : {
          "data" : [ "site:current-date" ],
          "op" : "\u003E",
          "value" : 1485351000
        }
      },
      { "data_is" : {
          "data" : [ "site:current-date" ],
          "op" : "\u003C",
          "value" : 1485365400
        }
      }
    ],
    "DO" : [ { "data_set" : { "data" : [ "result" ], "value" : "1" } } ],
    "PROVIDES VARIABLES" : [ "result" ]
  }
}

```

You should be able to import this rule in your own environment.

What this Rules Component does is "only" return a boolean (**1** or **0**), based on the condition if the site's current time (in GMT) is between `2017-01-25 14:30:00` and `2017-01-25 18:30:00`.

With that, we're coming close to an actual answer to your question, as detailed in Part 3 below.

# Part 3:

Head over to the "Block" settings for the block you want to conditionally hide. At the bottom of it's settings, within the typical "Visibility settings", there is now (after you enabled the Rules block visibility module as in Part 1) an extra tab labeled "*Rules*". Using that tab will allow you to select a "Rules Component" that will do what's documented below that selection list field, ie: "***Show this block only if the selected rule returns a positive value. Important: to be listed here, a block visibility rule must have specific parameters and return values.***".

And guess what, in my case I just selected my Rules Component from Part 2.

**Note**: it doesn't matter what type of block it is (created by a view, or something else), it works in all cases.

---
Tags: 7, views, panels, cron
---


# Question
Title: How to get all Taxonomy Term attached to Node?
The Node has attached two terms.

`Term::load($node->get('field_posts_category')->target_id);` only returns first item. How to get all Taxonomy Term attached to Node?

# Answer
> 4 votes
Use the method `referencedEntities()` to get all terms:

```
$terms = $node->field_posts_category->referencedEntities();

```

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


title: Problem with login page

text:
# Question
Title: Problem with login page
On my drupal website every page with "/nl" in the url, give an error. Only the home page works, because there is no "/nl" in the url.

Example: Home page: http://wnl.be/ All other menus, links, ... on the website give errors, such as http://www.wnl.be/nl/wagenpark

The big problem is that the login page also "/nl" contained in the url. You can test it: www.wnl.be?q=user/login

How can I fix this?

# Answer
Seems you have infinite redirection which causes the page not to load. (stops after x redirects)

It happens on every page (the once that load and the once that don't load) see my screenshot of the network tab to see it in action:
> 0 votes

---
Tags: 7
---


# Question
Title: Disable an parent link for dropdown menu but keep css
i have this menu : http://jsfiddle.net/aL7Xe/1000/

And I disabled the href link "bewerken" with

```
a[href="/test4/disabled"] {
  pointer-events: none;
}

```

But now my css does not show on that link, does anyone have any idea on how I can keep my css on that link but still have it disabled ?

# Answer
> 0 votes
Adding

```
  e.preventDefault();

```

under

```
 $('.topmenu').click(function(e){

```

will disable link redirection.

---
Tags: theming, javascript
---


title: Load an entity from a URI

text:
# Question
Title: Load an entity from a URI
I have a URI 'entity:node/27' and I want to load this entity, but I cannot find the correct helper function or class to use.

**I do not want to explode the string or regex the string**, I am fairly sure there is a function for this.

# Answer
> 9 votes
```
$params = Url::fromUri("internal:" . $source_uri)->getRouteParameters();
$entity_type = key($params);
$entity = \Drupal::entityTypeManager()->getStorage($entity_type)->load($params[$entity_type]);

```

---
Tags: 8, entities, uri
---


# Question
Title: Reuse/sync view mode display settings across entity bundles?
Assuming I have a number of entity bundles (e.g. node types) with a similar structure and behavior. Now I want to show a list of such entities/nodes. I want to use a view mode, e.g. "teaser", to display each node.

I could now configure the "teaser" view mode for all 4 node types, optionally with Display Suite. But the settings should be all the same.

So, which solutions do exist to have the same settings across entity bundles, and keep them synced?

Also, when exporting to a feature, I would prefer to avoid redundancy.

As far as I know, this is not currently possible with view modes in Drupal 7, due to how this feature works. But I am curious for out-of-the-box solutions that do the job.

*Disclaimer: This is a question I repeatedly was asking myself in the past. At the time I am writing this, I already created a solution that works for me. I am posting this as a Q/A to share it with others. meta*

# Answer
> 0 votes
Multiple solutions, pick what works best for you..

## View modes

If you really want to work with view modes, there might be ways to copy the settings around between bundles. This still leaves you with lots of redundancy. So maybe not the preferable solution.

## Views fields

If you work with Views, you can use views fields instead of view modes. These have their own advantages and drawbacks. You cannot use a layout (afaik). And now you cannot reuse the fields configuration across views.

So..

* views fields: reuse across entity bundles, but not across views.
* view modes: reuse across views, but not across entity bundles.

## Ctools content panes / panels

Panels configurations can be reused in different places.

I personally do not use them as much, so I am sure someone else could write more about it.

## Entity display plugin / Renderkit.

You can use EntDisP, to configure an entity display from multiple components. (This is using components from Renderkit.)

The module gives you a views row plugin, and a views field handler. So you can create an "entity display" for the entire row, or you can combine it with views fields.

It also gives you field formatters for entityreference, taxonomy term reference, paragraphs, and field collection.

You can configure the entity display in the place where you use it, so it will be stored as part of the view, field formatter, etc.

Or you can configure it as a "preset" with CFR Preset, so it will be stored independently and can be reused in different places. Such presets can be exported as features.

You can embed view modes in entity displays.

You can also embed entity displays in view modes using EntdispFieldUI.

---
Tags: 7, entities, display-suite
---


# Question
Title: How do I add a specific meta-tag to all the pages of a site?
I want to prevent Google from indexing my website. I know I need this meta tag added to the header.

```
<meta name="robots" content="noindex" />

```

How can I add this meta-tag to all the pages of a site?

# Answer
> 10 votes
You can use the Metatag module for this, in order to add meta tags to every page of your site:

If you want to do it by coding, it is possible to implement the theme\_preprocess\_html hook to add the meta tag manually:

```
function theme_preprocess_html(&$variables)
{

    $noindex = [
            '#tag' => 'meta',
            '#attributes' => [
                'name' => 'robots',
                'content' => 'noindex',
            ],
        ];
    $variables['page']['#attached']['html_head'][] = [$noindex, 'noindex'];
}

```

(more details here: https://stackoverflow.com/questions/35913739/add-meta-tag-to-head-in-drupal-8)

# Answer
> 4 votes
You can also add a `robots.txt` file with the following content in your docroot:

```
User-agent: *
Disallow: /

```

You can find more information about this in The Web Robots Pages.

---
Tags: 8, meta-tags
---


# Question
Title: How to Include custom tokens in the user register welcome mail
Is it possible to use custom tokens in the default user regitration welcome mail? I need to pass variables from a custom module. Is the solution to create a token in the custom module and include it into the mail?

# Answer
The user mail templates can be found at `example.com/admin/config/people/accounts`. The welcome mail for instance looks like this:

> \[user:display-name\],
>
> A site administrator at \[site:name\] has created an account for you. You may now log in by clicking this link or copying and pasting it into your browser:
>
> \[user:one-time-login-url\]
>
> This link can only be used once to log in and will lead you to a page where you can set your password.
>
> After setting your password, you will be able to log in at \[site:login-url\] in the future using:
>
> username: \[user:name\] password: Your password
>
> -- \[site:name\] team

As you can see there are already many tokens used.

Furthermore, Drupal does not distinguish between core tokens and those of modules. So if a textfield allows you to use core tokens (like this one), you can also use any other token. If you create a custom token, you will be able to use it in the mail. BUT, you must keep in mind that this mail template only has access to a select set of tokens (click the *Browse tokens* link below the textarea):

```
Current date    current-date    Tokens related to the current date and time.
Current page    current-page    Tokens related to the current page request.
Current user    current-user    Tokens related to the currently logged in user.
Random  random  Tokens related to random data.
Site information    site    Tokens for site-wide settings and other global information.
Users   user    Tokens related to individual user accounts.

```

When working with tokens, each module can define which tokens it handles (The `$data` array passed to `Token::replace()`). In this specific case, it only gets the `user` entity of the created user. Apart from that, several global tokens are always available, these are `Current date`, `Current page`, `Current user`, `Random` and `Site`.

So your custom token must be provided within the `user` or `site` type.
> 2 votes

---
Tags: 8, users, tokens
---


title: How can I programatically load a group?

text:
# Question
Title: How can I programatically load a group?
I have written this code to render a list of profiles (using the Profile module). It works fine.

```
// render profiles
$accounts = \Drupal\user\Entity\User::loadMultiple($uids);
$storage = \Drupal::entityTypeManager()->getStorage('profile');
if (!empty($storage)) {
  foreach ($accounts as $account) {
    $profiles[] = $storage->loadByUser($account, 'profile');
  }
  if ($profiles) {
    $content = \Drupal::entityTypeManager()
      ->getViewBuilder('profile')
      ->viewMultiple($profiles, 'teaser');
  }
}

```

I have applied the same logic to rendering a list of groups (using the Group module). It fails with the error below.

```
// render groups
$groups = \Drupal\group\Entity\Group::loadMultiple($ids);
$storage = \Drupal::entityTypeManager()->getStorage('group');
if (!empty($storage)) {
  foreach ($groups as $group) {
    $test[] = $storage->loadByGroup($group, 'my_group');  // FAILS HERE
  }
  /* if ($groups) {
    $content = \Drupal::entityTypeManager()
      ->getViewBuilder('group')
      ->viewMultiple($group, 'teaser');
  } */
}

```

> Fatal error: Call to undefined method Drupal\Core\Entity\Sql\SqlContentEntityStorage::loadByGroup()

What method should I use to load a group? or how should I programatically load a group?

Thanks

# Answer
Adding my comment as an answer:

`$groups = \Drupal\group\Entity\Group::loadMultiple($ids);` is all that is needed to load the groups based on IDs. `Group::loadMultiple()` does the storage bits already, so no need to duplicate the work.

So the full snippet would be something like:

```
<?php

$groups = \Drupal\group\Entity\Group::loadMultiple($ids);
if ($groups) {
  $content = \Drupal::entityTypeManager()
      ->getViewBuilder('group')
      ->viewMultiple($group, 'teaser');
}

```
> 4 votes

---
Tags: 8, group
---


title: How to recover from a borked cache?

text:
# Question
Title: How to recover from a borked cache?
The following steps lead to a situation where drush cc all would fail.

1. Build a site, with fields and stuff. Especially one or some fields for the user entity.
2. Install an alternative cache plugin, e.g. mongodb.
3. Change the site configuration. E.g. remove one of the fields on user entity.
4. Disable the alternative cache plugin, switch back to database cache.

Now the database cache contains really old data (or this is how I imagine it), still referencing fields that have long been deleted.

On drush cc all, drush first wants to bootstrap Drupal. Doing this, it also tries to load a user account for login. This lets it use cached data for user fields.

I get a crash with mysql exception from field\_sql\_storage\_field\_storage\_load(), because it tries to load non-existing fields.

I suppose this is just one example for a site being broked due to really old cache data, after switching the cache plugin.

How can one recover from this situation?

# Answer
> 2 votes
For me the following hack worked:

1. Edit `includes/cache.inc`. Let `function cache_get()` return FALSE.
2. Run `drush cc all`.
3. Revert the hack in `includes/cache.inc`.

I am not saying this is the best solution. But it did work for me, on a dev system. I am not sure I would recommend this on a production system.

Here is the hack:

```
 function cache_get($cid, $bin = 'cache') {
+  return FALSE;
+  # return _cache_get_object($bin)->get($cid);
-  return _cache_get_object($bin)->get($cid);
 }

```

---
Tags: 7, drush, caching
---


# Question
Title: Trying to use hierarchical select in exposed view filter - dont get the option
I have activated the Hierarchical select taxonomy views module, but when I add an exposed filter on my taxonomy term, I dont get an option to use the hierarchical select as a widget as the documentation says I should.

# Answer
Use Simple Hierachical Select module instead which works

> Simple hierarchical select defines a new form widget for taxonomy fields to select a term by "browsing" through the vocabularies hierarchy.
> 0 votes

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


# Question
Title: How can I limit and show only the first referenced node per node in a view?
I have content type A with a field that references nodes of type B. This is field with multiple values.

I need to show all the values of content type A, and include one of the fields of the referenced content type B (an image). So I created a view showing these fields.

The problem is that I just want to show the first result of content type B and eliminate the duplicates of content type A. So according to the post Only show first entity reference in views, I used the module Views Distinct. And it works, the problem is that I have more than 2000 nodes and the query is very very slow.

So the next thing I thought was to use the Infinite Scroll module to make it faster. And this works, but the problem now is that I need to group the results by a field, and with this module the header of each group is being repeated, every time results are loaded.

So I thought I could use the Delta for the reference field, and filter it to the nodes with delta = 0, but I don't know why the first value is not 0 is a different number. So this option is not valid.

Does anyone know how to show only the first reference with a good performance?

# Answer
> 1 votes
I think you were on the right track with the delta filter. I've had success with this method before. You should print the deltas as a part of your testing to try to determine why it isn't working properly. Also, make sure that you aren't using a relationship on the delta filter.

**\[Edit\]** If you continue to have issues with the deltas being inconsistent, then I would recommend the views field view option. It should be more performant than views distinct and, while not preferred, will get the job done.

Another option would be to implement your own reset delta logic on node A save (really not ideal though).

# Answer
> 3 votes
I can suggest you one solution which will probably help you with performance.

You can make use of views field view module.

You can use the view which you have created to render the fields of content type A and now create a separate view (as block) of content type B with current node ID as contextual filter and required relationship for the reference field and set limit to 1 or use delta as filter and call this view as field in the view in which you have rendered content type A fields.

EDIT: Second view can be called conditionaly wherever required, so is more handy if you require it only once in the parent view (by result count or once in header) OR get rendered it with every result of parent view.

---
Tags: views, entities
---


title: Reusing view field formatting?

text:
# Question
Title: Reusing view field formatting?
I have several views that display data from the same content type, Customer.

I had to decide whether the view should display the teaser and format the teaser in a custom node--customer.tpl.php or to use Views ability to specify exact fields and format those. I decided to use Views to format the fields (under Format-\>Show-\>Fields) based on the preference to configure rather than code.

However, I don't want to duplicate this field formatting for each view that needs to display customers. Is there a way to reuse the field formatting configuration from one view in a another? (besides cloning the entire view) And is there a way to keep them in sync?

# Answer
> 2 votes
The best way to do this is by using a display mode for the content you are trying to display. The whole purpose of display modes is to provide a way to render content in a consistent way across the site.

The field format for views is meant to provide granular control over the content displayed for that specific view. The best way to clone field formatting is to just clone the whole view and modify it from there; however, the first method is definitely the right way to do this.

**\[Edit\]** You can use the Entity View Modes module to create custom displays. Once the display is created, you can manage it from the "Manage Display" tab on the content type. If you need further customization to your display, Entity View Modes allows you to provide a custom template for each view mode.

---
Tags: 7, views, entities
---


# Question
Title: Theme a Panelized Content Type Not Working
I'm trying to add a content type to an existing site. I've added it, panelized it, added fields, and everything seems to be working well. There is a second panelized content type in this site that is being themed from a file titled `node--typename.tpl.php` and is working correctly.

I attempted to name mine `node--my-typename.tpl.php`, cleared all caches, but nothing works.

I `drush vset theme_debug 1` and checked for `tpl` suggestions but it doesn't really mention anything pertaining to theming the content type—just panelizer.

Is there a setting I'm missing here? I've combed through both content types and can't see a difference but one allows theming using `node--` files and the other doesn't.

# Answer
I figured out what I was doing wrong.

In my content type, under Panelizer \> Full Page Override \> Content I had to add "Rendered Node" to the main content area. This allowed me to use the `node--my-typename.tpl.php` file to theme this panelized content type.
> 0 votes

---
Tags: 7, theming
---


# Question
Title: SMS Framework - Multiple destination numbers
I'm using SMS Framework module to send sms from Drupal site; Clickatell is setted as my default gateway. Using Rules module I'm able to notify users via sms when new node is created, but i can only setup one destination number. Is there anyway to setup mutiple destination number?

A screenshoot of my rule configuration below:

# Answer
> 0 votes
Assuming your question is about D7, you could try to create a view (using the Views module) of those users that you want to send an SMS to.

After you succeeded in creating such view, you can *process the results of a VBO enabled view via Rules*, whereas your rule performs 2 Rules Actions (in the rule you already have in place):

* Load the VBO list of those users.
* Add a loop to perform a Rules Action "send an SMS" (similar to what your current rule already does), for each user contained in your Views results.

For more details, have a look at the tutorial "How to process the results of a VBO enabled view via Rules?".

---
Tags: rules
---


# Question
Title: How can I uninstall a module with entities in the db?
How can I uninstall a Drupal 8 module with entities in the db?

I have made a dev module that implement content entities created using the drupal console. I've added fields, views, and made some modifications. But, when I try to uninstall the module, there is a error:

```
The following reasons prevent the modules from being uninstalled:
There is content for the entity type: xxx

```

Where xxx is the entity type name. If I delete the entities manually or via code, I can disable the module. But I wanted a easier way, allowing the module to delete the entities itself. I tried using **hook\_uninstall()**, but apparently it is called after the triggering error.

I did't found the answer googling. Maybe my wording was wrong...

Anyaway. Any help would be apreciated

# Answer
There is some sort of a shortcut, but it might not be what you are looking for.

If you go the *Uninstall tab* of the *Extend page*, for all modules that define content entities you'll see:

The Remove content items link will delete all entities in a batch operation, after which you can uninstall the module. So you don't have to remove them one-by-one or from the database, but it requires some extra mouse clicks...

UPDATE

There is also `hook_module_preuninstall($module)`, which might be of help for you.
> 2 votes

---
Tags: 8, entities, installation
---


# Question
Title: How to add a comment form in VBO to add the same comment to mutiple nodes?
I am using "Comments" as a note option. I want to let users add the same comment to multiple nodes with the Views Bulk Operations (VBO) module.

How do I get the "Add Comment Form" in VBO to achieve this?

# Answer
> 1 votes
### Step 1

Use the Rules module to create a Rules Component, which includes whatever Rules Conditions you might need (if any), and with a Rules Action to **create an entity**, of type "Comment", whereas you specify some relevant parameters for that Rules Component, such as:

* The node to which the comment is to be added.
* The relevant options for the actual comment (such as the actual text of the comment).

Below is an example of a Rules Action that creates a comment (in Rules export format, use the Rules UI to import it in your own site):

```
{ "rules_add_a_comment_to_a_node" : {
    "LABEL" : "Add a comment to a node",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "comment_node" : { "label" : "Node to add comment", "type" : "node" },
      "comment_body" : { "label" : "Comment body", "type" : "text_formatted" },
      "comment_subject" : { "label" : "Comment subject", "type" : "text" }
    },
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "2" : "2" } }
        }
      }
    ],
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "comment",
            "param_subject" : [ "comment-subject" ],
            "param_node" : [ "comment-node" ],
            "param_author" : [ "site:current-user" ],
            "param_comment_body" : [ "comment-body" ]
          },
          "PROVIDE" : { "entity_created" : { "comment_created" : "Created comment" } }
        }
      }
    ]
  }
}

```

### Step 2

Create a view of the nodes to which some comment is to be added. Then transform that view into a view that uses Views Bulk Operations, and use the technique documented in "How to use Rules to create a custom bulk operation for a VBO view?". In doing so, you'll then be able to use the Rules Component from Step 1.

PS: this answer is for D7 ...

---
Tags: comments, views
---


title: GET method form is not processed

text:
# Question
Title: GET method form is not processed
I want to build kind of a search form in Drupal 8: On submit, it shall load itself again, but below the results shall rendered. And the URL shall contain the search term, so that the result page is linkable.

This is my minimal example. My current problem ist, that the submitted form value is not fed to `$form_state`.

```
public function buildForm(array $form, FormStateInterface $form_state) {

  $form_state->setMethod('get');

  $query = $form_state->getValue('query');
  // Unfortunately, this is empty, even after submit.

  $form['query'] = array(
    '#type' => 'textfield',
    '#title' => $this->t('Query'),
  );
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => $this->t('Search'),
  );

  return $form;
}

public function submitForm(array &$form, FormStateInterface $form_state) {
  $form_state->setRebuild();
  $form_state->setAlwaysProcess(TRUE);
}

```

When I comment out `$form_state->setMethod('get');`, it is working as I want: `query` is readable in the rebuild form and set as default value in the text field.

But with `setMethod('get');`, `query` is empty and no default is set.

I thought that `$form_state->setAlwaysProcess(TRUE);` makes sure the values get processed, even via GET method, as the documentation suggests. But apparently, something is missing. Any ideas, what?

# Answer
I could solve the problem myself, based on this solution for Drupal 7.

Instead calling the form directly in the router, I define a page callback in `my_module.routing.yml`.

```
my_module.form:
  path: '/my-module-form'
  defaults:
    _title: 'My module form'
    _controller: '\Drupal\my_module\Controller\MyModuleController::searchForm'

```

In `MyModuleController`, I load my form via the builder.

```
public function searchForm() {

  $form_state = new FormState();
  $form_state->setMethod('get');
  $form_state->setAlwaysProcess(TRUE);
  $form_state->setRebuild();

  $form = \Drupal::formBuilder()->buildForm('Drupal\my_module\Form\MyModuleSearchForm', $form_state);
  unset($form['form_build_id']);
  unset($form['form_id']);

  return $form;
}

```

The code of form then is like in the question above.
> 5 votes

---
Tags: 8, forms
---


title: Creating a custom 3up layout view?

text:
# Question
Title: Creating a custom 3up layout view?
On the homepage of my website, I would like to have a block which displays 3 links to inner pages like so:

Each would have the Title of The page, a teaser image that I would like to select to represent each of these links *(Since none of the inner pages have images used on them)*, a small summary and a link to the page. What's the best course of action for me to take in creating this? Would I create a custom view block to display this? If so, are any special settings needed and is there a way for me to select which picture is used through the views settings *(overrides?)*?

I feel as if this is quite the simple thing to achieve, yet I seem to be overthinking it as I can't come up with a proper solution which would make sense to me.

# Answer
> 2 votes
Multiple ways of doing this depending on what you feel like doing.

### Custom block type

Create a custom block type, add the fields you need, add them to a region and set to the homepage. Theme the twig files that relate to this block type.

### Paragraph type

You can set up a paragraph type to build this into the node itself. Create a paragraph type that has title, image, summary, and link - then a reference field on the host node that limits the cardinality to 3 total. Theme up the twig files that relate to this paragraph.

### Entity reference field on the node

You can even simply set a reference field to other nodes and let the editor enter what nodes they want to reference, and set the field formatter to a display mode (for example 'Call to Action' or 'Card'), and theme those twig files. Simply printing `{{ content.field_foo_reference }}` will render them as their view mode set in the field formatter. Fields like 'summary' can live on the referenced node - perhaps even a body field that is trimmed (look at adding Smart Trim for better trimming options on long formatted text fields).

Personally, I would go with the third method - it is the quickest of the three to do. I think you can even achieve this with core alone - something you can't do with the second method. It also puts all the work into the node form, instead of require editors to fool with the block system overview and create blocks to do this. Of course, you can also add this reference field on a block type and employ the same method - however since the homepage for me is almost always a node, I like to contain it in the same spot.

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