# Question
Title: Newbie question : where to put "advanced" page content?
It's been almost 3 years that I'm a web developer and I just started with Drupal 8. I have to say that's I'm feeling really confused by all the things in the Drupal worlds that you have to understand in order to create a website.

Here is the thing, I'm supposed to create a little website (3 pages for now) with a 100% custom appearance. I started by creating a new Drupal 8 theme with its libraries and dependencies and started coding the website's layout in twig. I added a few blocks in the theme's configuration (and in the twig) like a header block, two highlights blocks, a main content block and so on.

I'm at the point where I finished the layout and I'm supposed to add content of the 3 pages :

* A main page containing text, images, a thumbnail of the last posted photos album, and an overview of the two last posted articles.
* A form who's supposed to store the data somewhere (in the database I guess).
* A second form who's supposed to do quite the same.

My questions are :

* Since I have a very specific content for my three pages with HTML/CSS and Javascript, where am I supposed to put it ? Simply in 3 separated "Basic page" in the "Content" section of Drupal ? It seems way too simple. The "Basic page" content isn't supposed to be only text/images ?
* I'm using a "naked" Drupal. In order to create the forms and other special stuffs, I'm supposed to use modules, right ? Are there any that are mandatory ?

Thank you all in advance, and please excuse my English, it isn't my mother tongue.

# Answer
> 1 votes
IMHO it's easier to start with content, and add the design once the content structure is ready. Drupal tries to separate content and design as much as possible, so you can always change one and keep the other.

There are no mandatory modules, especially with Drupal 8 you can get very far without any additional modules.

Drupal stores the content of a page as "nodes". Nodes have a type, like "article" or "product". You can use the default node types that you get out-of-the-box, or define your own. Each node type has a number of fields, like a text fields, image fields, date fields, etc. You can enhance node types by adding additional fields. Drupal will take care of rendering those fields on a form, storing the content in the database, and displaying the content on the page. There is a lot more I could say about this, but I recommend that you read the documentation, especially the part about content structure.

---
Tags: nodes
---


# Question
Title: How can I include php file in my module without using composer?
I want include PHP file in drupal 8 module. What is the best way for it ?

# Answer
Outside of autoloading, the only option Drupal provides itself is `module_load_include()`, which literally

> Loads a module include file.
>
> Examples:

```
// Load node.admin.inc from the node module.
module_load_include('inc', 'node', 'node.admin');
// Load content_types.inc from the node module.
module_load_include('inc', 'node', 'content_types');

```

The final part of the description is worth taking in separately as it's important:

> Do not use this function to load an install file, use module\_load\_install() instead. Do not use this function in a global context since it requires Drupal to be fully bootstrapped, use require\_once DRUPAL\_ROOT . '/path/file' instead.

It's also worth noting this function won't be around forever, the plan is to move it completely into the module handler service.
> 2 votes

---
Tags: 8
---


# Question
Title: Exposed filters and contextual taxonomy description
A view called "Music".

Fields: "title", "image" Exposed filter: "category" (is a taxonomy-field = rock, jazz, salsa,...). Every taxonomy-term has a description.

When the visitor for example, selects "rock" the results are filtered. So far, so good.

But i want also want that when a "category" is selected, the description of the selected term is displayed above the results.

I think that could be done with an attachment and contextual filters, but i can't get it working.

# Answer
You may use tokens (replacement patterns). If you add the term description in your fields and exclude it from display, you will have access to `[description]` token in a `Global: Text area`, for example, added in the view header. Then, if you check `Use replacement tokens from the first row` and set your exposed form style on `Input required`, when a category is selected, results will be filtered and the term description related to this category will be displayed in the header.

EDIT : for Drupal 8 (sorry, still more a "7 guy" ^^), the token follows Twig syntax : `{{description_value}}`
> 1 votes

---
Tags: 8, views
---


# Question
Title: if i am on a node page how can i get one of the taxonomy terms for that node?
In drupal 8, if I am on a certain page, how can I get the taxonomy terms for one particular taxonomy that that node has ? I want to do this in a custom module

# Answer
i had to do it in three steps , not sure if there is an easier way:

```
$taxonomy=$node->field_taxonomy;
$taxonomy_value=$taxonomy->getValue();
$tid=$channel_value[0]['target_id'];

```
> 0 votes

# Answer
You should be able to access it via its field:

`$node->field_taxonomy->value`
> 2 votes

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


# Question
Title: Conditionally hide the node comments via preprocess function
I have learned how to hide the display of the author and the creation date of a node, depending on the content of a taxonomy field. Is it going to hide the comment on the same way?

```
function mytheme_preprocess_node(&$variables) {

  // check if this is the right content type where the field exists
  if ($variables['node']->getType() != 'article') {
    return;
  }

  // taxonomy field
  $field = $variables['node']->field_where_to_publish;

  if (!$field->isEmpty() && $field->entity->label() == 'public') {

    // How to hide the comment for this entity label?
  }

}

```

# Answer
> 4 votes
```
$variables['content']['comment']['#access'] = FALSE;

```

That should work, assuming you use the default comment field named "comment", otherwise whatever you named it. Comments are just a field, nothing special about them.

You can also check it directly in twig and not print it there.

---
Tags: 8, nodes, comments
---


# Question
Title: how to know if the page i am on is a node or not
with a custom module, in drupal 8, how can I test whether I am on a node entity or not, when i browse to that page?

If I do this $node = \Drupal::routeMatch()-\>getParameter('node'); I get an error if i'm not on a node.

# Answer
Getting the route parameter is not a problem, this returns NULL if the route parameter is not present. But you have to check the node is not NULL, before using it:

```
if ($node = \Drupal::routeMatch()->getParameter('node')) {
  $value = $node->field_name->value;
}

```
> 1 votes

# Answer
You can do:

```
if(\Drupal::routeMatch()->getRouteName() == 'entity.node.canonical'){
 //Do what you want.
}

```
> 1 votes

---
Tags: 8, nodes
---


# Question
Title: Automatically filling field in related content type
I have two similar content types on a Drupal 8 site: *groups* and *projects*. *Groups* can have child projects, but a project does not necessarily have a parent group. I have an entity-reference field on the *Project* content type, where a parent group can be added.

However, as I am setting up many different views, I would like these child projects to be added to the *Groups* nodes when users add parents to the *Project* nodes. In other words, I want to automatically update the field "Projects" on the related node of the "group" type.

How would I go about doing this? I see most people recommend showing a block on the node, but I would like to use this field in various views, so that won't work.

# Answer
Using CER ( https://www.drupal.org/project/cer ) as suggested by Nikko worked as intended. When adding a parent group, the project is added to the group node. Which means I can hide the field, and will make setting up the different views on the page 100x simpler.
> 1 votes

# Answer
So if I undersand you don't have any relation Groups -\> Projects? You just have a relation Projects -\> Groups (that you also call parents)? . And you want to show by views, Groups and their children (projects)?

If this is what you want you have several choices.

* Add many relationships in the view advanced filters in order to reach groups projects, (could be tricky).
* Add a field entity relationship Groups -\> project that you programmatically set on every projects insert/update/delete. Thanks to this it would be much more easier to build a view.
* create your own custom block, with your dedicated SQL query. listing all children of a group and attaching this block to all "groups" content type pages.
> 1 votes

# Answer
I don't think that create two references is a good option when you only need one in the project content type.

If you want create a view to show all the project of a group you should add in the view a Contextual Filter to the `field_related_research_group` field. If you want to show the view in a Group node page then you can chose the **Provide default value** option and as type **Content ID from URL**.

In your Filter Criteria the content type must be project.
> 0 votes

---
Tags: views, nodes
---


# Question
Title: How to handle with broken module installation
I prepared a module that has some issues. I tried to install it, but while installing it crashed. I'd like to make some tiny changes and reinstall it, but the module is set as installed. When I go to uninstall this page is no longer available, because while module was installing it provided some changes, so uninstall page crashes. I know how to uninstall a broken module, but this procedure is pure evil and it takes a wile. Is there, so the changes are rolled back if the module has some issues?

# Answer
> 1 votes
Before the module installation you export your site configuration with drush cex. You install your module and if it crash you import the saved configuration with drush cim.

---
Tags: 8
---


# Question
Title: drupal_get_form -- How do I include a JavaScript onClick event into the function results?
I have someone else's drupal\_get\_form code, where I was requested to have the form's button change color after clicking, while the user remains on that page.

The function's *rendered output* looks like this:

```
<form action="/mitreinstitute/my-institute" method="post" id="mi-custom-course-withdrawal-email-form-0" accept-charset="UTF-8">
 <div>
  <input type="submit" id="edit-submit" name="op" value="Withdraw Me" class="form-submit" />
  <input type="hidden" name="form_build_id" value="form-rpHwdhyCJfun0lRObhtuMWjehzOeNTHOeL9YCY-jQ84" />
  <input type="hidden" name="form_token" value="0tnkm6jb6PhZnpTNI16SLMq0XrkhZGKsDax7d3S9hIk" />
  <input type="hidden" name="form_id" value="mi_custom_course_withdrawal_email_form_0" />
 </div>
</form>

```

I cannot figure out to incorporate something like this JavaScript onClick function, so that it is merged into the form's rendered *submit* element:

# Answer
You can add Javascript to a form using the `#attached` property. So either in the form definition, or a hook\_form\_alter if you're altering a form you didn't code:

```
$form['#attached']['js'][] = drupal_get_path('module', 'MYMODULE') . '/foo.js';

```

In the JS file add what you need to, wrapping it in a Behavior to ensure events are reattached following AJAX calls:

```
(function($) {
  Drupal.behaviors.MYMODULE = {
    attach: function(context, settings) {
      $('#form-id').once('MYMODULE').submit(function() {
        // Do what you need to here
      });
    }
  };
})(jQuery);

```
> 2 votes

---
Tags: forms, javascript
---


title: Most recent posts drupal 8

text:
# Question
Title: Most recent posts drupal 8
I'm working on news portal using drupal 8.
I need to display most recent posts but there is a little tricky thing.
In that view should be most recent news including updated ones, BUT not if we edited the node because of grammar errors, just if we are adding new information in that post or changing the news in it.
I have '**updated field**' in post edit page where we enter the time of post update so I can use that for sorting also... We fill this field only if we update the news with new information like live blog or something like that.
So, there is **authored on** (creation date) sort option, and **node change** sort option in drupal 8, but my problem is that I don't want to get posts that are updated because of grammar errors...
Does anybody have some suggestions?
Thanks.

# Answer
> 1 votes
You can filter the view by the node created date, instead of the changed date.

Alternatively, you can add a date field to the node, "Published on", and use that instead. Drupal won't touch this field.

# Answer
> 1 votes
That's pretty straightforward as it goes:

1. Add a Boolean checkbox field to the content type, label it, "last edit was trivial", or similar
2. Make sure your content editors are aware they need to tick/untick the field when appropriate
3. Add the new field to your filters; done

---
Tags: views
---


# Question
Title: Drupal 8 Remove book child pages with in the content block
I am looking to not show Book child-pages within the content and only show them in sidebar region. So I anticipate not to hide them using css but remove the child-pages that gets called automatically within the main content (near to the end of the content block)

# Answer
> 0 votes
In D7 (not sure of D8) if you install Display Suite and enable the "Full Content" view mode for Books. You can then apply any layout you want to book pages and control where the book navigation goes for example.

Attempting to override the book behavior from Core can be very difficult ...

---
Tags: views, blocks, hooks
---


# Question
Title: how to get parent tids of a taxonomy term
I used this code to get the parent ids , but the result is a huge object . how do I get the parent id's and term names from the resulting object ?

```
 $ancestors = \Drupal::service('entity_type.manager')->getStorage("taxonomy_term")->loadAllParents($tid);

```

# Answer
In $ancestors you'll find an array of the parent terms starting with the term $tid itself:

```
$ancestors = \Drupal::service('entity_type.manager')->getStorage("taxonomy_term")->loadAllParents($tid);
$list = [];
foreach ($ancestors as $term) {
  $list[$term->id()] = $term->label();
}

```
> 33 votes

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


# Question
Title: more than one content type in a condition?
I'm using this as below described in my subtheme (Thanks to @4k4 and @Berdir):

```
function kanu_preprocess_node(&$variables) {
  if($variables['node']->getType() != 'test') {
    return;
 }
  $field = $variables['node']->field_where_to_publish;

  if (!$field->isEmpty() && $field->entity->label() == 'public') {
     $variables['display_submitted'] = FALSE;
     $variables['content']['comment']['#access'] = FALSE;
  }
}

```

How to write it for 3 different content type (with same field names)?

# Answer
You can use `in_array`.

```
$types = array('one', 'two', 'three');

if (!in_array($variables['node']->getType(), $types)) {
  // code
}

```
> 2 votes

---
Tags: 8, nodes
---


# Question
Title: How to use TinyMCE 4.5 with the WYSIWYG module?
I am using the WYSIWYG module on Drupal 7, but the only TinyMCE editor I can use is version 3.5. I would like to use the version found here. How can I install this?

# Answer
The previous version of the WYSIWYG module didn't support TinyMCE, but it does now.
> 0 votes

---
Tags: wysiwyg
---


# Question
Title: Use external class in drupal 8 module with file name and class name
I have created a module in drupal 8 . I need to use a class which is in external file .

File name : drupal.php

Class name : class newman{...}

In drupal.php ( have many classes ):

```
<?php
namespace Drupal\mymodulename\lib;
class newman{
   public function new(){
       $dp = 'TEST';
       return $dp;
   }
}
?>

```

In my controller :

```
<?php
namespace Drupal\mymodulename\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\mymodulename\lib\drupal;

class mmController extends ControllerBase {
    public function man() {
          $this->man=new newman();
          $build['test'] = [
                            '#markup' => $man->new(),
                           ];
    }
}

```

Error: Class 'Drupal\mymodulename\Controller\newman' not found in Drupal...

How can I fix it ?

# Answer
> 3 votes
Your `use` statement is wrong. It should be:

`use Drupal\mymodulename\lib\newman;` \- no Drupal on the end.

Aside from that, you should strive to inject dependencies in the constructor.

Also, there should not be a difference between the file name and classname. It makes it harder to debug and organize. The file should be named `newman.php` not `drupal.php`.

The error is referencing the fact that it cannot locate your class at the given namespace. It would help to brush up on PSR-4/autoloading in Drupal 8 as well as naming conventions and standards.

---
Tags: 8
---


# Question
Title: Placing Content Outside of Region Container
My custom bootstrap sub-theme has a main content region which is the place that all the main content is to go within a *.container* class.

The code for that section is as follows:

```
    {# Main #}
    {% block main %}
      <main role="main">
        <div class="container">
          <div class="row">

            {% if page.sidebar %}
              {% block sidebar %}
                <aside class="col-sm-3" role="complimentary">
                  {{ page.sidebar }}
                </aside>
              {% endblock %}
            {% endif %}

            {%
              set content_classes = [
                page.sidebar ? 'col-sm-9',
                page.sidebar is empty ? 'col-sm-12'
              ]
            %}
            <section{{ content_attributes.addClass(content_classes) }}>

              {% if page.announce %}
                {% block announce %}
                  <div class="announcements">{{ page.announce }}</div>
                {% endblock %}
              {% endif %}

              {% block content %}
                <a id="main-content"></a>
                {{ page.content }}
              {% endblock %}

            </section>

          </div>
        </div>
      </main>
    {% endblock %}

```

Now I want to create a couple view blocks on my homepage within this main content region but I'd like the backgrounds and content to extend outside the main container and be 100% of the screen width.

Is there a way for me to do this with my current code or is there another way to go about this?

# Answer
Following your structure one way could be:

Wrap your views block structure as shown below:

```
        </section> #Section ends
        </div> #Row ends
        </div> #Container ends

        #Full width, out of container
        [View_block] #View block out of container
        #Full width ends

        <div class="container"> #Container opens
        <div class="row"> #Row opens
        <section{{ content_attributes.addClass(content_classes) }}> #section opens
        # Rest of the content is in container...

```

This will maintain the original structure and places your views blocks outside of the container and within the main content. Even if this block is turned off, the page will not break.

Please modify as per your final output.
> 3 votes

---
Tags: 8, theming
---


# Question
Title: Link one title to a different page other than its content of a view page
I have a Drupal 8's views page in which Title and body of a specific content type is listed. I have enabled the title to link its content (node).

Supose if I have a list of 10 titles with its body listed, is there any way to override the link of one or two titles in order to redirect to a different page rather than its content/node.

# Answer
I could achieve this by using jquery. I attached a jquery in global library (To add jquery and css to drupal 8 refer this page)

I needed a url redirection while clicking on the link /node/7 from the views field to /another-page. The jquery for which is as follows

```
$('.view-class a[href$="node/7"]').attr('href', '/another-page');

```

This selects the anchor tag with the 'view-class' and href attribute value ends with 'node/7' and redirects to '/another-page'
> 0 votes

---
Tags: views, 8
---


title: How do I get comment form?

text:
# Question
Title: How do I get comment form?
In Drupal 7, comment form can be rendered using the following code.

```
drupal_get_form("comment_node_{$node->type}_form", (object) array('nid' => $node->nid));

```

How can I achieve the same in Drupal 8?

# Answer
> 7 votes
See https://api.drupal.org/api/drupal/core%21modules%21comment%21src%21CommentLazyBuilders.php/function/CommentLazyBuilders%3A%3ArenderForm/8.2.x.

You create a comment entity and then get its form.

```
<?php
$values = array(
    'entity_type' => $commented_entity_type_id,
    'entity_id' => $commented_entity_id,
    'field_name' => $field_name,
    'comment_type' => $comment_type_id,
    'pid' => NULL,
  );
$comment = \Drupal::entityTypeManager()->getStorage('comment')->create($values);
$form = \Drupal::service('entity.form_builder')->getForm($comment);

```

---
Tags: forms, comments
---


# Question
Title: How to hide/remove "Request New password" link in Drupal 7?
I am using 'Login Block' to access Intranet pages from our website. I used 'Login Block' on www.example.com/common-intra page to login into intranet section.

I am using userprotect module to hide profile/username/password information from the users when they logged in into Intranet section (www.example.com/common-intra) with universal account.

But, I wanted to hide/remove "Request New password" link from Intranet Login page:

I found this module, haven't used yet though: https://www.drupal.org/project/noreqnewpass

Is there any other easy way to just hide **"Request New password"** link from that Intranet Login page?

I still want this tab on general login page such as: www.example.com/user But, I just want to hide it from the www.example.com/common-intra page.

I also tried to hide it with css.

This is my page source code:

```
<div class="panel-separator"></div><div class="panel-pane pane-block pane-user-login common-intra pane-user common_login_button"   class="panel-pane pane-block pane-user-login common-intra pane-user common_login_button">

    <div class="pane-content">
        <form action="/common-login?destination=node/16" method="post" id="user-login-form" accept-charset="UTF-8"><div><div class="form-item form-type-textfield form-item-name">

      <label for="edit-name">Username <span class="form-required" title="This field is required.">*</span></label>

     <input type="text" id="edit-name" name="name" value="" size="15" maxlength="60" class="form-text required" />
    </div>

<div class="form-item form-type-password form-item-pass">
  <label for="edit-pass">Password <span class="form-required" title="This field is required.">*</span></label>

 <input type="password" id="edit-pass" name="pass" size="15" maxlength="128" class="form-text required" />
</div>

    <div class="item-list">
<ul>
<li class="first last"><a href="/user/password" title="Request new password via e-mail.">Request new password</a></li>
</ul></div>

<input type="hidden" name="form_build_id" value="form-_xyzabc" />

```

```
<div class="form-actions form-wrapper" id="edit-actions"><input type="submit" id="edit-submit" name="op" value="Log in" class="form-submit" /></div></div></form>  </div>

  </div>

```

I gave class name `'common-intra'` to user login block to my node template.

```
.common-intra ul li{
    display: none;
}

```

I also tried:

```
.panel-pane pane-block pane-user-login common-intra pane-user common_login_button ul li
    {
          display: none;
    }

```

# Answer
this will remove it from the render array before it is printed. In your theme's template.php, add:

```
function MYTHEME_form_alter(&$form, &$form_state, $form_id)
{
    if($form_id == 'user_login_block')
    {
        $form['links']['#markup'] = '<div class="item-list"><ul><li class="first"><a href="/dev/user/register" title="Create a new user account.">Create new account</a></li></ul></div>';
    }
}

```

Basically, it is just rewriting the markup for the links in the user login block. You can tweak this to theme as well. this should only apply to the user block
> 4 votes

# Answer
You can use the No request new password module:

> Remove "Request new password" link from block and user page.

I tested the module and it works fine.

Another solution is to put this in your page.tpl.php just before the render($tabs) line this code. Works fine on Drupal 7 :

```
<?php
if(isset($tabs['#primary'][2]['#link']['path']) && $tabs['#primary'][2]['#link']['path'] == 'user/password'){
   hide($tabs['#primary'][2]);
}
?>

```

You can find other solutions in:

> Disabling 'Request new password' on Login block
>
> How to remove menu tabs front login page?
> 2 votes

# Answer
As per API reference, in your custom module you can:

`function MYMODULE_menu_alter(&$items) {
 // Example - disable the page at node/add
 $items['user/password']['access callback'] = FALSE;
}`

https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook\_menu\_alter/7.x
> 1 votes

---
Tags: 7, users, blocks
---


title: Programmatical use of Search API

text:
# Question
Title: Programmatical use of Search API
Problem: Need to run my own searches programmatically with Search API. Every google result I find is geared toward teaching non-developers how to use the module with Views with no results on doing it like I want.

Information:

* Using local database service instead of Solr or any other.
* Have data not stored in database that will appear alongside other results.
* Content will be grouped in "type" tabs.
* Not using Views for various reasons.
* Have Facets API enabled but no clue how to use it either.

Why: Because I want to have the search page be at /site-search and without /node/keyword after the page argument. Also will be asked to customize this beyond the scope of other modules that may provide the same type of functionality. And I want to learn how to do this but have not found any tutorials or other insight on how to accomplish it.

The rest: I have created my search page and on it I am executing the search with:

```
$term = $_SESSION['my-search']['term'];
$server = search_api_server_load('database');
$index = search_api_index_load('default_node_index');
$query = new SearchApiQuery($index);
$query->keys($term);
$query->fields(array('title','body:value'));
$srv= new SearchApiDbService($server);
$result = $srv->search($query);

```

The session variable is set when a search form is submitted then redirects the user to /site-search to perform the search and show the results.

If I output $result I see it's an array with different information including a result set that is an array of node ids and their scores.

I could run through those, grabbing the node and displaying the results myself but I figure there's got to be some other method for rendering the results of the search. I haven't found it though and that's the problem.

I've been looking through the different classes in Search API and Facet API and can't find anything in them that seem like they would build result output.

Any help with this will be appreciated.

Results example:

```
Array
(
[result count] => 11
[results] => Array
    (
        [37] => Array
            (
                [id] => 37
                [score] => 15.7503318786621
            )

        [39] => Array
            (
                [id] => 39
                [score] => 7
            )

        [40] => Array
            (
                [id] => 40
                [score] => 5
            )

        [31] => Array
            (
                [id] => 31
                [score] => 4
            )

        [33] => Array
            (
                [id] => 33
                [score] => 1
            )

        [36] => Array
            (
                [id] => 36
                [score] => 1
            )

        [1] => Array
            (
                [id] => 1
                [score] => 1
            )

        [15] => Array
            (
                [id] => 15
                [score] => 1
            )

        [16] => Array
            (
                [id] => 16
                [score] => 1
            )

        [27] => Array
            (
                [id] => 27
                [score] => 1
            )

        [35] => Array
            (
                [id] => 35
                [score] => 0.980873763561249
            )

    )

[warnings] => Array
    (
    )

[ignored] => Array
    (
    )

[performance] => Array
    (
        [complete] => 0.0033111572265625
        [preprocessing] => 0.00053095817565918
        [execution] => 0.0027379989624023
        [postprocessing] => 4.2200088500977E-5
    )

)

```

# Answer
> 4 votes
Have you looked at the Search API pages module. It uses the Search API module and creates a custom search page. You could probably look at that module for clues on how to implement what you are trying to do. The module itself might even provide a lot of the functionality that you are looking for.

# Answer
> 1 votes
Here's my solution in about 100 lines -- a little simpler than pages...

```
define('SEARCH_QUERY_TERM', 'query');
define('SEARCH_PAGE_TERM', 'page');
define('SEARCH_LIMIT_TERM', 'limit');
define('SEARCH_DEFAULT_LIMIT', 10);

/**
 * Implements hook_menu().
 */
function my_module_menu() {
    $items['search'] = array(
        'title' => 'Search',
        'page callback' => 'my_module_page',
        'access callback' => TRUE,
        'type' => MENU_CALLBACK,
    );

    return $items;
}

/**
 * My Module Search Functions
 */

function my_module_page() {
    $build = array(
        'form' => drupal_get_form('my_module_form'),
        'results' => array('#theme_wrappers' => array('container')),
    );

    foreach (my_module_result() as $eid => $entity) {
        $build['results'][$eid] = entity_view('node', array($entity), 'teaser');
    }

    return $build;
}

function my_module_form($form, &$form_state) {
    list($query, $page, $limit) = my_module_params();

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

    return $form;
}

function my_module_form_submit($form, &$form_state) {
    $values = $form_state['values'];
    $query = isset($values['query']) ? $values['query'] : '';
    $form_state['redirect'] = array('search', array('query' => array('query' => $query)));
}

function my_module_params() {
    $query = '';
    $page_number = 0;
    $limit = SEARCH_DEFAULT_LIMIT;
    $params = drupal_get_query_parameters();

    if (isset($params[SEARCH_QUERY_TERM])) {
        $query = $params[SEARCH_QUERY_TERM];
    }
    if (isset($params[SEARCH_PAGE_TERM]) && is_numeric($params[SEARCH_PAGE_TERM])) {
        $page_number = $params[SEARCH_PAGE_TERM];
    }
    if (isset($params[SEARCH_LIMIT_TERM]) && is_numeric($params[SEARCH_LIMIT_TERM])) {
        $limit = $params[SEARCH_LIMIT_TERM];
    }

    return array($query, $page_number, $limit);
}

function my_module_result() {
    $index_id = 'default_node_index';

    list($keys, $page_number, $limit) = my_module_params();
    $offset = $limit * $page_number;

    $options = array(
        'search id' => 'node:default',
    );

    $query = search_api_query($index_id, $options)->keys($keys);

    if ($limit > 0) {
        $query->range($offset, $limit);
    }

    $results = $query->execute();
    $results = isset($results['results']) ? $results['results'] : array();

    return entity_load('node', array_keys($results));
}

```

---
Tags: 7, search
---


# Question
Title: When to use drush_log() or drush_set_error()?
I just trying to show an error message with drush and I see that you can achieve this with

```
drush_set_error('NON_EXISTENT', 'Message');

```

and with

```
drush_log('Message', 'error');

```

In both cases you will see the same error message, I read the functions documentation but I can't figure out are the differences between they?

# Answer
In general, you should avoid using the status code 'error' when calling `drush_log` directly. Use `drush_log` to signal non-terminal events, usually with a status code of `warning` or `notice`.

If a function fails and cannot continue, the best thing to do is to exit with `return drush_set_error(...);`. This sets internal state, so that Drush knows that there was an unrecoverable error, and calls through to `drush_log('Message', 'error');`.
> 5 votes

---
Tags: drush
---


# Question
Title: Executing a method of a custom entity after all instances have been built
I'm putting together a private message module. Conversations threads are a custom entity within the module. A thread can potentially appear twice on a page - once in the 'inbox' (a block), and once as the main content of the page. I'm wrapping the rendered threads with a div that I'm attaching in an override of EntityViewBUilder::view(). If the user has not viewed the thread, I'm adding a class of 'unread-thread' to the div wrapper.

Where I'm running into a problem, is finding a place to mark the thread as 'read'. If I do it at the end of EntityViewBuilder::view(), then the class is only applied to the first instance of the thread on the page, since it's already been marked read by the time it comes to the next instance of the thread on the page. I want the class to be part of the wrapper on all instances of the thread on the page.

So I need to find somewhere to mark a thread as read, but only after all instances on the page have passed through EntityViewBuilder::view(). I'm thinking a post-render hook may be good, but I'm not finding one. Does anyone have any suggestions?

# Answer
You can use an event for this, a RESPONSE event with a low priority or a TERMINATE event. See for example `UserRequestSubscriber::onKernelTerminate`:

```
/**
   * Updates the current user's last access time.
   *
   * @param \Symfony\Component\HttpKernel\Event\PostResponseEvent $event
   *   The event to process.
   */
  public function onKernelTerminate(PostResponseEvent $event) {
    if ($this->account->isAuthenticated() && REQUEST_TIME - $this->account->getLastAccessedTime() > Settings::get('session_write_interval', 180)) {
      // Do that no more than once per 180 seconds.
      /** @var \Drupal\user\UserStorageInterface $storage */
      $storage = $this->entityManager->getStorage('user');
      $storage->updateLastAccessTimestamp($this->account, REQUEST_TIME);
    }
  }

```
> 1 votes

# Answer
Here is my final solution. I've commented the code to track what is happening. Basically the steps are:

1) Register a handler to be executed on page request

2) In that handler, retrieve the data necessary to perform the action that needs to happen

3) Execute the action

```
namespace Drupal\private_message\Event;

use Drupal\Core\Session\AccountProxyInterface;
use Drupal\private_message\Entity\PrivateMessageThread;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\FinishRequestEvent;

class PrivateMessageEventSubscriber implements EventSubscriberInterface {

  /**
   * The current user
   *
   * @var \Drupal\Session\AccountProxyInterface
   */
  protected $currentUser;

  /**
   * Construct a PrivateMessageEventSubscriber object
   *
   * @param \Drupal\Session\AccountProxyInterface $currentUser
   *   The current user
   */
  public function __construct(AccountProxyInterface $currentUser) {
    $this->currentUser = $currentUser;
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    // Register an event listener for when the request finishes
    $events[KernelEvents::FINISH_REQUEST][] = ['onKernelTerminate'];

    return $events;
  }

  /**
   * Register the thread access for the user. This is called on the end
   * of the page request
   *
   * @param \Symfony\Component\HttpKernel\Event\FinishRequestEvent $event
   */
  public function onKernelTerminate(FinishRequestEvent $event) {
    // Retrieve the thread ID for the current page
    $private_message_thread_id = $event->getRequest()->get('private_message_thread_id');
    if ($private_message_thread_id) {
      // Load the thread
      $private_message_thread = PrivateMessageThread::load($private_message_thread_id);
      if ($private_message_thread) {
        // Perform the action at the end of the page load
        $private_message_thread->updateLastAccessTime();
      }
    }
  }
}

```
> 1 votes

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


title: update 8.2.7 to 8.3.0 with composer

text:
# Question
Title: update 8.2.7 to 8.3.0 with composer
I want to update with composer (running the drupal composer drupal project), and already succesfully updated 8.2.6 - 8.2.7, but now it doesnt update to 8.3.0

```
$ composer update drupal/core --with-dependencies
Package "drupal/core" listed for update is not installed. Ignoring.
Loading composer repositories with package information
Updating dependencies (including require-dev)
Nothing to install or update
Generating autoload files

```

# Answer
Taken from: here

You need to make sure that **drupal/core** is in the require part of your **composer.json** and not the **replace** part, it won't work otherwise.

Haven't tested it yet, but it explains the **Package "drupal/core" listed for update is not installed. Ignoring.** message.

In case someone's looking for the way to upgrade using drush:

```
drush up drupal

```
> 1 votes

# Answer
I had a dull moment and was running in the web directory, not in the parent directory with the composer.json.
> 1 votes

---
Tags: 8, updating, composer
---


# Question
Title: How can I access to created "View modes" in views and create a block of it?
I created a *"View modes"* in `Structure> Display-modes> View` and I'm now trying to get access to it in views so i can be able to create a block of it.

By default in Drupal it's possible to create a block of `teasers` and `full posts` but I'm going to create a block of my own "View modes",

I cleared my cash several times but howsoever i try the "View modes" that's i created doesn't show in "Block display settings" dropdown menu and I can't create a block of it.

# Answer
> 4 votes
Just skip this part of creating a View. Don't create a block or page display yet (that's what I do) and work on a master view. When you go select rendered content as a field, you will have view modes you created as options. Show "Content" as a view mode.

See this for more:

---
Tags: views, 8, nodes
---


title: How to set up an iTunes podcast?

text:
# Question
Title: How to set up an iTunes podcast?
This question about podcasting in Drupal 7 recommends the Views RSS iTunes elements module, which hasn't had any commits on the Drupal 8 dev branch since 2014. (tutorial for D7)

The iTunes RSS tag documentation shows that the tags are not very complex, and indeed the iTunes elements module (D7) documentation shows that there are only about a dozen tags that need to be set up for an iTunes-compatible podcast.

So my question is, do any of the additional features of D8 compared to D7 provide a way to configure this with just the modules in core, or am I going to have to code something to generate an RSS feed that meets the iTunes podcasting requirements?

I was hoping to be able to use something like a Views theming template to just rewrite all the tags in the template and publish the feed that way.

# Answer
> 1 votes
Just because there hasn't been a commit for ages doesn't mean it's totally not worth investigating further - as you say the tags are not complicated so probably that hasn't changed.

I had a quick look and the first issue on the issue queue is for the 8 version and it's to do with how libraries are loaded, which I believe did change as 8 moved along. Someone's posted a patch in Dec 16 so not that long ago and it's marked as 'needs review', so best would be to try it out and report back there as to whether that works or not, if so and something else doesn't work then create another issue if you can't fix it yourself, or post another patch if you can.

If you use composer to install Drupal 8, for example using: https://github.com/drupal-composer/drupal-project

then you can also apply the patch in the patches section of your composer.json by adding the link to the patch so it can find it: https://www.drupal.org/files/issues/views\_rss\_itunes-fatal\_error\_call\_to\_undefined\_function\_libraries\_load-2839012-3.patch

This is kinda how it works - if you wait it may never arrive, and if you can't do the above it's all googleable skills.

---
Tags: 8, feeds
---


title: D8 Search api - taxonomy pages

text:
# Question
Title: D8 Search api - taxonomy pages
Is there way to replace /taxonomy/term/% on search api views?

I was trying create new indexed views with Content datasource: Categories » Taxonomy term » Term ID but when i visit page, it's always return 404.

Please, any suggestions.

# Answer
One way to facilitate this is to use Taxonomy Views Integrator. You will be able to create views and set vocabulary or terms to use those views instead of the default taxonomy page from core Drupal.
> 2 votes

---
Tags: views, taxonomy-terms, search
---


# Question
Title: Create / Edit node and continue editing on same page after submit
D7 has module "Save & Edit".

There are any solutions for D8?

# Answer
> 4 votes
The Save & Edit module is a very basic module. It comprises of 6 total functions, so a port could be done less than a day.

Alternatively, if the your requirement is to just save editing progress while keeping the editor window up, the Autosave form module does that.

If you're looking to go the custom code route, some simple jQuery form manipulation can add a button which can trigger a form redirection & submit. For example:

```
// Set the form destination to the edit form and submit it.
jQuery('form.node-form').attr('action', '/node/<NID>/edit?destination=node/<NID>/edit');
jQuery('.node-form').submit();

```

---
Tags: 8
---


# Question
Title: Add theme settings field to theme-settings.php in d8 is not working for me
I followed the documentation on drupal.org to add a field to the theme-settings.php but there must be a mistake in code.

I have a filed called advertisement and a theme called tv so I tried to copy and paste the code and altered the names where to alter theme the files I created in particular are as follows:

/themes/tv/templates/system/thme-settings.php

```
#}
function tv_form_system_theme_settings_alter(&$form,
\Drupal\Core\Form\FormStateInterface &$form_state, $form_id = NULL) {
  // Work-around for a core bug affecting admin themes. See issue
 #943212.
  if (isset($form_id)) {
    return;

$form['tv_advertisement'] = array(
    '#type'          => 'textfield',
    '#title'         => t('Widget'),
    '#default_value' => theme_get_setting('tv_advertisement'),
    '#description'   => t("Place this text in the widget spot on your
 site."),
  );
}
$tv_advertisement = theme_get_setting('tv_advertisement');

```

in /themes/tv/config/install/tv.settings.yml I put this:

```
tv_advertisement: blue bikeshed

```

My /themes/tv/tv.theme file contains:

```
<?php
/**
 * @file
 * Theme functions
 */

// Include all files from the includes directory.
$includes_path = dirname(__FILE__) . '/includes/*.inc';
foreach (glob($includes_path) as $filename) {
  require_once dirname(__FILE__) . '/includes/' . basename($filename);
}

 function tv_preprocess_node(&$variables) {
 $variables['tv_advertisement'] =
 theme_get_setting('tv_advertisement');
 }

```

The last thing I did was

```
drush cr

```

to clear the cache

When I go to the themes settings page there are only the default fieds displayed but the new one does not show up

If anyone has a clue what I am doing wrong and is able to enlighten me I would be very pleased.

Thank you

# Answer
> 0 votes
Try to remove this code:

```
  if (isset($form_id)) {
    return;

```

The hook interface of hook\_form\_system\_theme\_settings\_alter is hook\_form\_system\_theme\_settings\_alter(&$form, \Drupal\Core\Form\FormStateInterface $form\_state).

You can remove the third parameter:

```
 $form_id = NULL

```

---
Tags: forms
---


# Question
Title: How to use Rules to set a value for a multi-value field?
I'm trying to create an Order reference on Products when ever a new order is created. I have installed the "Order Reference" module and created an Order reference field on my product type.

Next I created the following rule:

* Rules Event: After saving a new commerce line item
* Rules Conditions:

1. Data comparison ( \[commerce-line-item:type\], Data value: Product )
    2. Data comparison ( \[commerce-line-item..., Data value: NAME OF TYPE )
* Rules Action: Set data value \[commerce-line-item..., Value: \[commerce-line-item:order\]

The above rule works fine as long as i limit the Order Reference field to 1 value, but as soon as it is set to multiple the rule breaks.. i get the following error for the action:

> Error: The data type of the configured argument does not match the parameter's value requirement.

I'm new to the Rules module and a kind a lost here. Any help?

Below is the exported rule:

```
{
  "rules_test_test_order_ref": {
    "LABEL": "test test order ref",
    "PLUGIN": "reaction rule",
    "OWNER": "rules",
    "REQUIRES": [
      "rules",
      "entity"
    ],
    "ON": {
      "commerce_line_item_insert": []
    },
    "IF": [
      {
        "data_is": {
          "data": [
            "commerce-line-item:type"
          ],
          "value": "product"
        }
      },
      {
        "data_is": {
          "data": [
            "commerce-line-item:commerce-product:type"
          ],
          "value": "iq_test_event"
        }
      }
    ],
    "DO": [
      {
        "data_set": {
          "data": [
            "commerce-line-item:commerce-product:field-order-reference"
          ],
          "value": [
            "commerce-line-item:order"
          ]
        }
      }
    ]
  }
}

```

# Answer
> 1 votes
Looks like you could just use the "Add to list" Rules Action. And since your question is about a multi-value field, for sure you should NOT use a Rules Action like "Set a data value", which is used to set assign a single value to a field (which seems to be what you've tried, a common mistake when using the Rules module for such fields).

Refer to the answer to "How to set multiple values to an unlimited Term Refence field with Rules" for "some" more details ...

PS: I'm assuming this question is about D7.

# Answer
> 0 votes
If anyone should be looking for the same functionality i found a solution, creating my own action, in this post :)

Update values of multiple value field programmatically? (Rules action)

---
Tags: commerce, rules
---


# Question
Title: When to use mapping or sequence to define an array in a schema file?
I need to define an array in my onlyone.settings.yml file to store this values:

```
onlyone_node_types:
  book: book
  test: test

```

In my onlyone.schema.yml file I have this:

```
module.settings:
  type: config_object
  label: 'Only One settings'
  mapping:
    onlyone_node_types:
      type: sequence
      label: 'Configured content types to have Only One node'
      sequence:
        type: string
        label: 'Content type machine name'

```

But I don't know if I need to use a sequence or a mapping type in my case.

I read in the Configuration schema/metadata page this:

> Note that you may also encounter a slightly different sequence definition where the type of the sequence items is defined as a strictly one item list. This format is deprecated and will be removed in Drupal 9:

So, I don't know if I need to use mapping or sequence in my case to define my array.

# Answer
A sequence is an unlimited list of identically structured elements. A mapping is a limited set of keys, each key has a possibly different structure.

Your key has node types, so you're storing a list of node type ids, which means a sequence with an inner type string. Exactly what you have.

If you'd use a mapping, you could *only* store book and test, but test could be an integer (or mapping, or sequence, ...) while book is a string.

The note has nothing to do with sequence vs mapping, it just refers to an old way of defining the type in the sequence and would look like this:

```
onlyone_node_types:
  type: sequence
  label: 'Configured content types to have Only One node'
  sequence:
    -  type: string
       label: 'Content type machine name'

```

PS: I'd would convert that to a numbered list, which will then be stored like this:

```
onlyone_node_types:
  - book
  - test

```
> 12 votes

---
Tags: 8, configuration
---


# Question
Title: How can I unset / remove a paragraph component from within template_preprocess_node?
In Drupal 7, I need to be able to selectively remove paragraph components from a given node. Which parts of the $variables array need to be unset?

# Answer
Pretty easily it seems. Something like the following does the job for removing the first component, for example:

`function THEME_preprocess_node(&$variables) {
 unset($variables['content']['field_landing_page_components'][0]);
 }`
> 2 votes

---
Tags: theming, paragraphs
---


title: add new menu items after existing items

text:
# Question
Title: add new menu items after existing items
When I create a page and add a menu link, it appears above the existing menu items (in the menu tree). Can this be changed so that new items flow under existing items?

# Answer
> 0 votes
Yes, it's possible. You have to change the "Weight". If you put a weight greater than the other menu links, the last will appear below.

---
Tags: 8, navigation
---


# Question
Title: How can i add my slideshow images into default slideshow?
I cannot change my slideshow images into default slideshow in my corporateclean theme. I am using drupal 7. Anybody help me how can i add my content in that theme. I am new to drupal.

# Answer
> 1 votes
According to this issue there is no interface for changing the slides. You should do it in code.

In the page.tpl.php file, you'll find multiple pieces of code like this:

```
<!--slider-item-->
    <div class="slider-item">
        <div class="content container_12">
            <div class="grid_12">

            <!--slider-item content-->
            <div style="float:left; padding:0 30px 0 0;">
            <img class="masked" src="<?php print base_path() . drupal_get_path('theme', 'corporateclean') ;?>/mockup/slide-1.jpg"/>
            </div>
            <h2>Sample product name</h2>
            <strong>General</strong><br/>
            <em>Client name</em><br/>
            <br/>
            Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
            <div style="display:block; padding:30px 0 10px 0;"><a class="more" href="#">Tell me more</a></div>
            <!--EOF:slider-item content-->

            </div>
        </div>
    </div>
    <!--EOF:slider-item-->

```

Those are your slides and that is where you can edit them. But if you are not tech savvy, you could also choose to disable the default slider (appearance \> corporate clean settings \> disable slideshow) and implement another slide show module like views slideshow.

By using another module you can use 'normal' content for the slides and position the slideshow as a block. There are plenty of tutorials and youtube videos. If you run into trouble you are free to ask here for help again.

---
Tags: theming, nodes
---


# Question
Title: Drupal module Date 2.7 update - Database Table name
I just updated the Drupal7 module ***Date*** from 2.9 to 2.10. There is a database table update that acccompanies that module update. What is the name of the database table that is updated? (or can you direct me where to find that information?)

Attaching screenshot of the database update performed when installing the date module. What are ***Date text widgets***?

# Answer
> 1 votes
It doesn't matter what tables are being updated, you can just go to `/update.php` of your site (you need to be logged in first) to apply these updates. You don't do them manually.

To find what was updated, you can look in the `CHANGELOG.txt` if the module has one, or, look in the install file for the module being updated within Date. It should have an applicable update hook that will show you (in code) what is being changed.

This is a list of everything that was changed in the last release.

---
Tags: 7, updating
---


# Question
Title: How can I show all registered users per event in Calendar?
I am using Entity Registration together with Calendar. I'm trying to list all registered users in the event, but I don't know how to configure the view properly. Take a look at this image:

I only want one listing of the event and then all the registrants inside that entry. Now it lists one event per registrant.

The view is like this:

# Answer
> 0 votes
I figured this out by creating a seperate view for registrants and then with the module Views field View I could show that view inside the Calendar view

---
Tags: users, entities, datetime
---


title: Pages broken after update

text:
# Question
Title: Pages broken after update
I have recently attempted to update from Drupal 8.2 to 8.3. After updating, all pages that use Display Suite do not render correctly. The markup generated contains a bunch of "\<\>" instead of the proper markup, and when I go do Display Suite configuration, all custom of fields of the node types that previously were used are do not show up in the list of fields to be placed in the layout elements. Anyone have idea as to how to troubleshoot something like this?

# Answer
> 1 votes
For Drupal 8.3.x you need to update Display Suite as well to 8.3.x (as is stated on the module page: https://www.drupal.org/project/ds).

> ### IMPORTANT NOTICE
>
> Due to changes in core a new version is created.
>
> * Drupal 8.2 or lower: Use Display Suite 8.2
> * Drupal 8.3 or higher: Use Display Suite 8.3

Maybe that's what causing all your problems; possibly, updating the module will solve your issues.

---
Tags: display-suite
---


# Question
Title: Is there an automatic way to convert old versioning conventions?
**Background**

I'm applying updates (including security updates) to a Drupal 8 site.

**Problem**

When I run composer update, I'm getting the following error multiple times: `The requested xxxxx package exists as yyyyy but these are rejected by your constraint.` :

```
    Loading composer repositories with package information
    Updating dependencies (including require-dev)
    Your requirements could not be resolved to an installable set of packages.

          Problem 1
            - The requested package drupal/devel 8.* exists as drupal/devel[dev-

1.x, 1.x-dev, 1.0.0-rc1, 1.0.0-beta1, 1.0.0-alpha1] but these are rejected by your constraint.
      Problem 2
        - The requested package drupal/migrate_tools 8.* exists as drupal/migrate_tools[dev-3.x, 3.x-dev, dev-2.x, 2.x-dev, dev-1.x, 1.x-dev, 3.0.0-beta1, 2.0.0, 2.0.0-rc1, 2.0.0-beta1, 1.0.0, 1.0.0-beta1] but these are rejected by your constraint.
      Problem 3
        - The requested package drupal/migrate_upgrade 8.* exists as drupal/migrate_upgrade[dev-3.x, 3.x-dev, dev-2.x, 2.x-dev, dev-1.x, 1.x-dev, 3.0.0-rc1, 3.0.0-beta1, 2.0.0, 2.0.0-rc1, 2.0.0-beta1, 1.0.0] but these are rejected by your constraint.
      Problem 4
        - The requested package drupal/admin_toolbar 8.* exists as drupal/admin_toolbar[dev-1.x, 1.x-dev, 1.19.0, 1.18.0, 1.17.0, 1.16.0, 1.15.0, 1.14.0, 1.13.0, 1.12.0, 1.11.0, 1.10.0, 1.9.0, 1.8.0, 1.7.0, 1.6.0, 1.5.0, 1.4.0, 1.3.0, 1.2.0, 1.1.0, 1.0.0] but these are rejected by your constraint.
      Problem 5
        - The requested package drupal/libraries 8.* exists as drupal/libraries[dev-3.x, 3.x-dev] but these are rejected by your constraint.
      Problem 6
        - The requested package drupal/pathauto 8.* exists as drupal/pathauto[dev-1.x, 1.x-dev, 1.0.0-rc1, 1.0.0-beta2, 1.0.0-beta1, 1.0.0-alpha3, 1.0.0-alpha2, 1.0.0-alpha1] but these are rejected by your constraint.
      Problem 7
        - The requested package drupal/honeypot 8.* exists as drupal/honeypot[dev-1.x, 1.x-dev, 1.24.0, 1.23.0, 1.22.0, 1.21.0, 1.19.0-beta14, 1.19.0-beta13, 1.18.0-beta6, 1.18.0-beta5, 1.18.0-beta4, 1.18.0-beta3, 1.18.0-beta2, 1.18.0-beta1, 1.18.0-alpha15, 1.16.0-beta11, 1.16.0-beta10, 1.16.0-beta6, 1.14.0-beta5, 1.14.0-beta4, 1.14.0-beta3, 1.14.0-beta2, 1.14.0-beta1] but these are rejected by your constraint.
      Problem 8
        - The requested package drupal/metatag 8.* exists as drupal/metatag[dev-1.x, 1.x-dev, 1.0.0, 1.0.0-beta12, 1.0.0-beta11, 1.0.0-beta10, 1.0.0-beta9, 1.0.0-beta8, 1.0.0-beta7, 1.0.0-beta6, 1.0.0-beta5, 1.0.0-beta4, 1.0.0-beta3, 1.0.0-beta2, 1.0.0-beta1] but these are rejected by your constraint.
      Problem 9
        - The requested package drupal/mollom 8.* exists as drupal/mollom[dev-1.x, 1.x-dev, 1.2.0, 1.1.0, 1.0.0, 1.0.0-rc2, 1.0.0-rc1, 1.0.0-beta1, 1.0.0-alpha5, 1.0.0-alpha4, 1.0.0-alpha3, 1.0.0-alpha2, 1.0.0-alpha1] but these are rejected by your constraint.
      Problem 10
        - The requested package drupal/smtp 8.* exists as drupal/smtp[dev-1.x, 1.x-dev, 1.0.0-beta2, 1.0.0-beta1, 1.0.0-alpha2, 1.0.0-alpha1, 1.0.0-alpha0] but these are rejected by your constraint.
      Problem 11
        - The requested package drupal/token 8.* exists as drupal/token[dev-1.x, 1.x-dev, 1.0.0-rc1, 1.0.0-beta2, 1.0.0-beta1, 1.0.0-alpha2, 1.0.0-alpha1] but these are rejected by your constraint.
      Problem 12
        - The requested package drupal/simple_sitemap 8.* exists as drupal/simple_sitemap[dev-2.x, 2.x-dev, dev-1.x, 1.x-dev, 2.9.0, 2.8.0, 2.7.0, 2.6.0, 2.5.0, 2.4.0, 2.3.0, 2.2.0, 2.1.0, 1.11.0, 1.10.0, 1.9.0, 1.8.0, 1.7.0, 1.6.0, 1.5.0, 1.4.0, 1.3.0, 1.2.0, 1.1.0, 1.0.0] but these are rejected by your constraint.
      Problem 13
        - The requested package drupal/superfish 8.* exists as drupal/superfish[dev-1.x, 1.x-dev, 1.0.0-rc6, 1.0.0-rc5, 1.0.0-rc4, 1.0.0-rc3, 1.0.0-rc2, 1.0.0-rc1] but these are rejected by your constraint.
      Problem 14
        - The requested package drupal/google_analytics 8.* exists as drupal/google_analytics[dev-2.x, 2.x-dev, 2.1.0, 2.0.0, 2.0.0-rc1] but these are rejected by your constraint.
      Problem 15
        - The requested package drupal/video_embed_field 8.* exists as drupal/video_embed_field[dev-1.x, 1.x-dev, 1.4.0, 1.3.0, 1.2.0, 1.1.0, 1.0.0, 1.0.0-rc8, 1.0.0-rc7, 1.0.0-rc6, 1.0.0-rc5, 1.0.0-rc4, 1.0.0-rc3, 1.0.0-rc2, 1.0.0-rc1] but these are rejected by your constraint.
      Problem 16
        - The requested package drupal/masquerade 8.* exists as drupal/masquerade[dev-2.x, 2.x-dev, 2.0.0-beta1, 1.0.0-beta1] but these are rejected by your constraint.
      Problem 17
        - The requested package drupal/extlink 8.* exists as drupal/extlink[dev-1.x, 1.x-dev, 1.0.0, 1.0.0-alpha3, 1.0.0-alpha2, 1.0.0-alpha1] but these are rejected by your constraint.
      Problem 18
        - The requested package drupal/embed 8.* exists as drupal/embed[dev-1.x, 1.x-dev, 1.0.0, 1.0.0-rc3, 1.0.0-rc2, 1.0.0-rc1] but these are rejected by your constraint.
      Problem 19
        - The requested package drupal/entity_embed 8.* exists as drupal/entity_embed[dev-1.x, 1.x-dev, 1.0.0-beta2, 1.0.0-beta1, 1.0.0-alpha3, 1.0.0-alpha2, 1.0.0-alpha1] but these are rejected by your constraint.
      Problem 20
        - The requested package drupal/node_view_permissions 8.* exists as drupal/node_view_permissions[dev-1.x, 1.x-dev, 1.0.0] but these are rejected by your constraint.
      Problem 21
        - The requested package drupal/paragraphs ^8.1@RC exists as drupal/paragraphs[dev-1.x, 1.x-dev, 1.1.0, 1.0.0, 1.0.0-rc5, 1.0.0-rc4, 1.0.0-alpha2, 1.0.0-alpha1] but these are rejected by your constraint.
      Problem 22
        - The requested package drupal/simple_gmap 8.* exists as drupal/simple_gmap[dev-1.x, 1.x-dev, 1.2.0, 1.1.0, 1.0.0] but these are rejected by your constraint.
      Problem 23
        - The requested package drupal/entity_browser 8.* exists as drupal/entity_browser[dev-1.x, 1.x-dev, 1.0.0-rc2, 1.0.0-rc1, 1.0.0-beta4, 1.0.0-beta3, 1.0.0-beta2, 1.0.0-beta1, 1.0.0-alpha12, 1.0.0-alpha11, 1.0.0-alpha10, 1.0.0-alpha9, 1.0.0-alpha8, 1.0.0-alpha7, 1.0.0-alpha6, 1.0.0-alpha5, 1.0.0-alpha4, 1.0.0-alpha3, 1.0.0-alpha2, 1.0.0-alpha1] but these are rejected by your constraint.
      Problem 24
        - The requested package drupal/dropzonejs 8.1.x-dev exists as drupal/dropzonejs[dev-1.x, 1.x-dev, 1.0.0-alpha6, 1.0.0-alpha5, 1.0.0-alpha4, 1.0.0-alpha3, 1.0.0-alpha2, 1.0.0-alpha1] but these are rejected by your constraint.
      Problem 25
        - The requested package drupal/inline_entity_form 8.* exists as drupal/inline_entity_form[dev-1.x, 1.x-dev, 1.0.0-beta1, 1.0.0-alpha6, 1.0.0-alpha5, 1.0.0-alpha4, 1.0.0-alpha3, 1.0.0-alpha2, 1.0.0-alpha1] but these are rejected by your constraint.
      Problem 26
        - The requested package drupal/file_browser 8.1.x-dev exists as drupal/file_browser[dev-1.x, 1.x-dev, 1.0.0-alpha4, 1.0.0-alpha3, 1.0.0-alpha2, 1.0.0-alpha1] but these are rejected by your constraint.
      Problem 27
        - The requested package drupal/sitemap ^8.1 exists as drupal/sitemap[dev-2.x, 2.x-dev, dev-1.x, 1.x-dev, 1.3.0, 1.2.0, 1.1.0, 1.0.0, 1.0.0-rc2, 1.0.0-rc1, 1.0.0-beta3, 1.0.0-beta2, 1.0.0-beta1, 1.0.0-alpha1] but these are rejected by your constraint.
      Problem 28
        - The requested package drupal/redirect 8.1.0-alpha1 exists as drupal/redirect[dev-1.x, 1.x-dev, 1.0.0-alpha4, 1.0.0-alpha3, 1.0.0-alpha2, 1.0.0-alpha1] but these are rejected by your constraint.

```

**Root cause**

I think this might be related to the move to a new package manager address ("endpoint) which appears to be using a different versioning convention on the basis of the errors. Obviously I would want to follow the new versioning system if that is the new standard.

Here's how I have changed my composer.json accordingly to use the new package manager, here is the relevant snippet of my git diff showing what I changed from and to:

```
     "repositories": [
         {
             "type": "composer",
-            "url": "https://packagist.drupal-composer.org"
+            "url": "https://packages.drupal.org/8"^M
+        },^M
+        {^M
+            "type": "composer",^M
+            "url": "https://packagist.org"^M
         },

```

**Question about possible solutions**

The only solution I can think of at the moment is for me to attempt to guess the new version of each "package" (i.e. Drupal module), one by one and edit the composer.json file.

This might not be too bad to do if it is a one off, but I wondered if there is any definitive conversion utility to map between the old and new versioning. Even though perhaps it is a bit of pain to for a one of, it might be more cumbersome for those who are upgrading multiple sites which dozens of modules.

Can anyone advise on automation, please? Thank you for your help.

Just to I've also done the following in prep, before doing the composer update:

```
composer self-update
cleared composer cache (by removing the folder to force it to be rebuilt)

```

I've done some research but not found anything about automation.

**Annotated Research:**

# Answer
> 1 votes
Solution for me that got me past that error was to do a global find/replace all of `"8.*"` with `"*"` in my `composer.json` and also for specific versions rewrite them in the format convention for the new package manager, a bit of guesswork. Here's my full changes shown as a diff (i.e. the original with - prefix, followed by the new with the + prefix):

```
-               "drupal/devel": "8.*",
-        "drupal/migrate_tools": "8.*",
-               "drupal/migrate_upgrade": "8.*",
-               "drupal/admin_toolbar": "8.*",
-        "drupal/coder": "8.2.5",
-        "drupal/libraries": "8.*",
-        "drupal/pathauto": "8.*",
-               "drupal/honeypot": "8.*",
-               "drupal/metatag": "8.*",
-        "drupal/mollom": "8.*",
-               "drupal/smtp": "8.*",
-        "drupal/token": "8.*",
-               "drupal/simple_sitemap": "8.*",
-        "drupal/superfish": "8.*",
-        "drupal/google_analytics": "8.*",
-        "wkse/google_tag": "^8.0",
-        "drupal/video_embed_field": "8.*",
-        "drupal/masquerade": "8.*",
-        "drupal/extlink" : "8.*",
-        "drupal/embed" : "8.*",
-        "drupal/entity_embed" : "8.*",
-        "drupal/node_view_permissions": "8.*",
-        "drupal/paragraphs": "^8.1@RC",
-        "drupal/simple_gmap": "8.*",
-        "drupal/entity_browser": "8.*",
-        "drupal/dropzonejs": "8.1.x-dev",
-        "drupal/inline_entity_form": "8.*",
-        "drupal/file_browser": "8.1.x-dev",
-        "drupal/sitemap": "^8.1",
+               "drupal/devel": "*",^M
+        "drupal/migrate_tools": "*",^M
+               "drupal/migrate_upgrade": "*",^M
+               "drupal/admin_toolbar": "*",^M
+        "drupal/coder": "^2.5",^M
+        "drupal/libraries": "*",^M
+        "drupal/pathauto": "*",^M
+               "drupal/honeypot": "*",^M
+               "drupal/metatag": "*",^M
+        "drupal/mollom": "*",^M
+               "drupal/smtp": "*",^M
+        "drupal/token": "*",^M
+               "drupal/simple_sitemap": "*",^M
+        "drupal/superfish": "*",^M
+        "drupal/google_analytics": "*",^M
+        "wkse/google_tag": "*",^M
+        "drupal/video_embed_field": "*",^M
+        "drupal/masquerade": "*",^M
+        "drupal/extlink" : "*",^M
+        "drupal/embed" : "*",^M
+        "drupal/entity_embed" : "*",^M
+        "drupal/node_view_permissions": "*",^M
+        "drupal/paragraphs": "*",^M
+        "drupal/simple_gmap": "*",^M
+        "drupal/entity_browser": "*",^M
+        "drupal/dropzonejs": "*",^M
+        "drupal/inline_entity_form": "*",^M
+        "drupal/file_browser": "*",^M
+        "drupal/sitemap": "^1.3",^M
         "enyo/dropzone": "4.2.0",
         "desandro/masonry": "3.3.1",
         "desandro/imagesloaded": "3.1.8",
         "mehrpadin/superfish": "2.0",
-        "drupal/redirect": "8.1.0-alpha1"
+        "drupal/redirect": "*",^M
+        "drupal/redis": "1.0-beta1"^M

```

**Update**

In the end as a final solution. I set each module to a specific version, based on the latest available stable or if not, then latest rc, beta or alpha from each module's project page on drupal.org But I had to change the versioning convention from drupal.org to what composer understands e.g. 8.x-1.0 on drupal.org will be 1.0.0 in composer. Thanks Berdir for your input.

This approach gives me control over what versions to use. I set each module to a specific version, based on the latest available stable or if not, then latest rc, beta or alpha from each module's project page on drupal.org But other people might necessarily need an earlier version of certain modules depending on what they are doing. The overall point is that specific version are used instead of the range notation that would allow composer to choose. It really depends on what one needs to do but I like the ability to choose specific versions and then choose to modify when newer versions come out.

---
Tags: 8, updating, composer
---


# Question
Title: Create test and development copy of a production site
I have a Drupal8 site on my hosting account. I created a copy from the database; I create a copy of the code.

Both the copies I used should be a copy of my production site. I imported the SQL into a new database. I changed the settings of the copied Drupal code to point to my new database.

When I go to the browser and look at local install I can only get to the install page.

Can anyone please point out where I am going wrong?

# Answer
> 3 votes
You have a problem with your settings.php file.

* Check if the name is correct.
* Check if the database is set correctly.
* Try to access in command Line to the database.
* Check rights of your files.
* Try to clear the cache with drush cr.

---
Tags: migrations
---


# Question
Title: How can I display the of result count of a view in its header?
Without writing using any Drupal db functions, how can I display the total/count/number of results of a view in its Header?

# Answer
> 4 votes
Do you not mean these predefined value(s) in the Header area ?

Return a view's total\_rows in Drupal 7 without php filter?

You could count the number of rows using PHP in views\_pre\_render() ... but I bet this is what the above is doing already ....

# Answer
> 1 votes
No need to use any php code.

you need the token module to be enabled along with the view of course.

1) Go to the view in question. 2) Click "Add" next to either "Header" or "Footer" in the center of the view. 3) Choose "Global: Result summary" 4) Click "Apply (All displays)" 5) On the next screen, you can chose tokens to put into the "Display" area. Here are the tokens you can use:

@start -- the initial record number in the set @end -- the last record number in the set @total -- the total records in the set @name -- the human-readable name of the view @per\_page -- the number of items per page @current\_page -- the current page number @current\_record\_count -- the current page record count @page\_count -- the total page count

Once you've chosen your options, click "Apply (All displays)".

7) You can put something like: Displaying @start - @end of @total.

Hope it helps.

# Answer
> -1 votes
**Warning: this tip requires enabling the core `PHP Filter` module, which opens up security concerns that could potentially allow the entry of PHP code into the site in ways that you may not want, if permissions are not configured correctly.**

Here is how using the core `PHP Filter` module:

1. In your view, add a header element of type `Global PHP`
2. Then add this snippet to text/php field in the header

`<?php echo $view->total_rows; ?>`

That should do it. There are a tonne more variables in the `$view` array.

Edit: As @Motot suggested, added security note.

---
Tags: 7, views
---


# Question
Title: Is it currently possible to install Drush locally on a Windows 10 PC?
Is it possible to install & use Drush locally on a Windows 10 Notebook to manage Drupal sites (on shared hosting) online? I have so far searched in vain, may be in wrong places. The places I see downloads or documentation, none seems to include Windows or in case of some tutorial on Youtube, the links related to drush on drush.org, do not seem to exist any more, such as that for "composer for Windows".

I would appreciate some specific guidance as a newbie on this.

Thank you & kind regards

# Answer
> 0 votes
You can install Drush on Windows using composer - http://docs.drush.org/en/7.x/install/

You can get composer from - https://getcomposer.org/doc/00-intro.md#installation-windows

In theory you can manage a remote site with Drush, but you have to have ssh access to the remote server. If you have ssh access, you are better off just logging in and running it on the server. If you have multiple sites across multiple servers, then setting up site aliases in Drush makes more sense.

# Answer
> 0 votes
Yes, you can install and use Drush on Windows 10 (and 7). The problem is to install the requirements:

* PHP
* Several Unix tools

You don't need Composer to install Drush 8, but Drush 9 (which is the next stable release) will also require Composer.

Typically you get PHP by installing a WAMP and you get the Unix tools by installing Bash with friends - for example MSYS. There is also Cygwin. And there is an interesting "Windows Subsystem for Linux" on Windows 10 ...

Anyway, this quickly gets complicated. That is why many people just use for example Acquia Dev Desktop which among many things gives you a working Drush. I assume the cleanest solution is to install the subsystem for Linux, but I haven't tried it myself.

PS! You can of course also go the virtual machine route - using virtualization to install a Linux server on your computer. Drupal VM is a very interesting project.

---
Tags: drush
---


# Question
Title: User can input multiple terms, results can tagged as some or all of those terms, but not other terms
I think I'm going to have to make a custom operator for this, but I figured I might as well ask in case I'm missing something obvious.

Let's say I have (in D7) three nodes tagged with colours:

Node 1

* blue
* green

Node 2

* yellow
* red

Node 3

* blue
* red

Node 4

* blue

The user selects red, blue, and green from the exposed filter in a view. This view should return Node 1, Node 3, and Node 4, but not Node 2 (as it is tagged with yellow). Using the "has taxonomy term" filter, the operators "is all of" and "is one of" don't work here, as the first one returns nothing, and the second returns Node 2.

To make things even more complex, I'll need to do this with two different filters in the view (with different sets of taxonomy terms), as well as have a standard "is one of" filter on a third taxonomy term set.

Am I missing a simple solution with this, or do I need to write a custom operator/filter? Thanks!

# Answer
> 0 votes
So if I understand this correctly, you only want the nodes that have all the checked values (and not a subset). So if I checked only blue, only node 4 will be returned and not 1 and 3?

I think you'd be best of to write a custom filter, based on the 'is one of' filter. With that you can select nodes that have the terms attached and than drill down the filter.

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


# Question
Title: Attaching two or more jQuery files to a theme
I was trying to add some jQuery files to a theme (to do some simple css logics). I could add one jQuery file by defining as follows

In the custom theme folder I edited themes.libraries.yml and added the following

```
global-scripts:
  js:
    js/jqueryfile1.js: {}
  dependencies:
    - core/jquery

```

and then I wrote my jquery code within inside custom\_theme\_folder/js/jqueryfile1.js as

```
(function ($){
Drupal.behaviors.myModuleBehavior = {
    attach: function(context, settings) {
        $(document).ready(function(){

            //code goes here

            });
        });
    }
};
})(jQuery);

```

Everything was fine till now. But when I'm trying to add my next file(jqueryfile2.js) only the the latest (jqueryfile2.js) is taking in action. I can see the previous file is also called in the DOM while checking the source but the code is not executing. After adding my second jQuery my libraries.yml will look like

```
global-scripts:
  js:
    js/jqueryfile1.js: {}
    js/jqueryfile2.js: {}
  dependencies:
    - core/jquery

```

At this point jqueryfile2.js is only taking in action not the first file. And there will be both my jquery files within inside the js folder and is called to the document.

# Answer
> 1 votes
By default, multiple local files will be aggregated where possible. To disable this for a file, set its 'preprocess' flag to false.

```
mymodule:
  version: 1.x
  js:
    js/custom.js: {preprocess: false}
  dependencies:
    - core/jquery
    - core/jquery.ui

```

# Answer
> 0 votes
You can try like the example

```
maintenance-page:
  version: VERSION
  js:
    js/mobile.install.js: {}

install-page:
  version: VERSION
  js:
    js/mobile.install.js: {}

drupal.nav-tabs:
  version: VERSION
  js:
    js/nav-tabs.js: {}

```

Taken from Seven theme **seven.libraries.yml** file.

# Answer
> 0 votes
Try this code to add js file to your custom module, mymodule.libraries.yml.

```
mymodule:
  version: 1.x
  js:
    js/custom.js: {}
  dependencies:
    - core/jquery
    - core/jquery.ui

```

---
Tags: theming, 8
---


# Question
Title: Programmatically Place View With Defined Fixed Contextual Filter
I'm currently using the starter module which adds the Twig function `place_view()`. This works well in most cases, however I'd like to be able to pass another parameter to populate the fixed value given in a contextual filter.

**This would be my contextual filter settings:**

**Here's the `place_view()` Twig function:**

```
public function place_view($name, $display_id = 'default') {
  $drupal = \Drupal::service('renderer');
  $view = views_embed_view($name, $display_id);

  if(! is_null($view)) {
    return $drupal->render($view);
  }

  return null;
}

```

Preferably I'd like to be able to use `place_view()` with a parameter to adjust that fixed value. It'd be even better if I could somehow reference the contextual filter I wanted to adjust the fixed value of.

Hopefully that all made sense, thanks in advance.

# Answer
> 3 votes
Use views\_embed\_view:

```
function views_embed_view($name, $display_id = 'default') {
  $args = func_get_args();
  // Remove $name and $display_id from the arguments.
  unset($args[0], $args[1]);

  $view = Views::getView($name);
  if (!$view || !$view->access($display_id)) {
    return;
  }

  return [
    '#type' => 'view',
    '#name' => $name,
    '#display_id' => $display_id,
    '#arguments' => $args,
  ];
}

```

Btw. Twig Tweak maps this function one to one:

```
  {# This accepts views arguments as well. #}
  <dt>View:</dt>
  <dd>{{ drupal_view('view_name', 'page_1') }}</dd>

```

**Example**

So if you want to filter the node 123 in the contextual filter you've shown in the question, you use this as third argument:

PHP

```
views_embed_view('view_name', 'block_1', '123');

```

TWIG (using the module Twig Tweak)

```
{{ drupal_view('view_name', 'block_1', '123') }}

```

---
Tags: 8, views
---


# Question
Title: Drupal 7.53 pathauto pattern field do not transliterate
I created a new field in on a content type I have on my application (Drupal 7.53), then in /admin/config/search/path/patterns I have set a pattern to this type of content as the following:

\[node:field-nw-sitemap:0:url:path\]/\[node:field\_titulo\_url\].

I expected to have a result like:

**mysite/subpath/new-content** it works fine on development environment, but in homolog, witch is online, the return to the url is **mysite/subpath/New%20Content**. Has anyone been here before? Help please. Thanks.

# Answer
> 0 votes
I have tested several times and looked all over the internet, in one test I was able to reproduce the problem in dev environment. The problem was that the filed name contained the keyword "url", the problem persisted with the word "path", once I changed the field machine name to field\_caminho everything worked fine.

---
Tags: path-aliases
---


# Question
Title: Can not disable the default blocks available under block layout
I installed Drupal 8.3 and I am facing the following issue: There is no disable region available under block layout, but the same is available under Drupal 8.2.6.

Is this an issue with Drupal core or with the theme I am using?

# Answer
Not an issue, please read release notes and under heading "Improved site building and administration:"

Removed the 'disabled' region from block administration.

Now there is an option to "**Disable**" block.
> 0 votes

---
Tags: blocks
---


# Question
Title: Programmatically change select field options in contact form
I'm currently rendering a contact form programmatically in a block plugin like so.

```
    $type = 'contact_message';
    $bundle = 'my_contact_form_name';
    $values = array();
    if (\Drupal::entityManager()->getDefinition($type)->hasKey('bundle')) {
        $bundle_key = \Drupal::entityManager()->getDefinition($type)->getKey('bundle');
        $values     = array($bundle_key => $bundle);
    }
    $entity = \Drupal::entityManager()
        ->getStorage($type)
        ->create($values);

    if ($entity instanceof EntityOwnerInterface) {
        $entity->setOwnerId(\Drupal::currentUser()->id());
    }

    $form = \Drupal::entityManager()
        ->getFormObject($type, 'default')
        ->setEntity($entity);

    $my_rendered_form = \Drupal::formBuilder()->getForm($form);
        $content[] = [
            '#type'    => 'html_tag',
            '#tag'     => 'h1',
            '#value'   => 'My Form Title',
            'form'    => $my_rendered_form,
        ];

```

It grabs and renders the form just fine. But the form has a select field and I want to alter the options for it. This is because the options should be dynamically generated based off the values of certain nodes. I already have a field called 'my\_select\_field' but I'm not sure how to change the values from it. When using die(print\_r($my\_rendered\_form\['my\_select\_field'\])); I receive a very large array and the my\_select\_field, and the test data I put in it appears in many locations in the array. My ultimate goal would be to accomplish something like this

```
$form['my_select_field']['#options'] = [
    1 => 'My new option 1',
    2 => 'My new option 2',
    3 => 'My new option 3',
];

```

How would I alter the options in a select field in a programmatically rendered contact form?

UPDATE: I found '#options' in the array

```
        [#options] => Array
            (
                [test1] => Drupal\Core\Field\FieldFilteredMarkup Object
                    (
                        [string:protected] => Test 1
                    )

                [test2] => Drupal\Core\Field\FieldFilteredMarkup Object
                    (
                        [string:protected] => Test 2
                    )

                [test3] => Drupal\Core\Field\FieldFilteredMarkup Object
                    (
                        [string:protected] => Test 3
                    )

                [test4] => Drupal\Core\Field\FieldFilteredMarkup Object
                    (
                        [string:protected] => Test 4
                    )

            )

```

But the options are objects rather than strings I can edit. I should probably also mention that the select field I have is set to multiple checkboxes.

EDIT: I'm willing to use a form alter hook if that is necessary. But if that's the case the same question applies.

UPDATE 2: I attempted altering the form using the hook form alter method like so

```
        $form['my_select_field']['widget']['#options'] = [
            1 => 'New option 1',
            2 => 'New option 2',
        ];

```

And the new options do appear, but now when I submit the form I receive the error

> The value you selected is not a valid choice.

# Answer
> 2 votes
This is probably not a good use case for the core version of contact form based on entity forms. You have not only to take care of the validation in the form api, but also on the entity level. If you want to do this, here is a tutorial: https://chromatichq.com/blog/dynamic-default-and-allowed-values-list-fields-drupal-8

In contrast Webform provides a very flexible handling of select options. You can edit the options separately from the form in predefined options lists and then you can modify the predefined options dynamically, see these examples:

```
/**
 * Implements hook_webform_options_WEBFORM_OPTIONS_ID_alter().
 */

function mymodule_webform_options_test_alter(array &$options, array &$element) {
  $options += [
    'four' => t('Four'),
    'five' => t('Five'),
    'six' => t('Six'),
  ];
}

/**
 * Implements hook_webform_options_alter().
 */
function mymodule_webform_options_alter(array &$options, array &$element, $id) {
  if ($id == 'custom') {
    $options = [
      'one' => t('One'),
      'two' => t('Two'),
      'three' => t('Three'),
    ];
  }
}

```

---
Tags: 8, forms
---


title: Why doesn't my code work?

text:
# Question
Title: Why doesn't my code work?
I am really getting frustrated with this. In my theme I have a script file that is working. I am adding a new function to deal with some div but nothing happen. Cleared the cache...tried different things...nothing is working.

The following code is working perfectly fine when tested in jsfiddle, but in my site...nothing at all.

html code output:

```
<div class="cal-full">
  <a href="/race/charlton-park-winter-monster-race-10k-2016-11-12">title</a>
</div>
<div id="cal-events-tooltip-4734" class="cal-events-tooltip cal-events-tooltip_hide">
  <h4 class="cal-entry-title summary"><a href="/race/event">title</a></h4>
  <div class="cal-event-body">
     <div class="cal-event-thumb">
     logo
     </div>
      <div class="cal-event-description"><p>dsfdsfsdfsdfsdfsdfsdfdfs</p>    </div>
     <span class="events-arrow"></span>
  </div>

```

in my js script:

```
$(document).ready(function () {

$(".cal-full").mouseover(function() {

        $(this).siblings('.cal-events-tooltip').addClass('cal-events-tooltip_show');
    $(this).siblings('.cal-events-tooltip').removeClass('cal-events-tooltip_hide');

    });

$(".cal-full").mouseout(function() {

        $(this).siblings('.cal-events-tooltip').removeClass('cal-events-tooltip_show');
    $(this).siblings('.cal-events-tooltip').addClass('cal-events-tooltip_hide');

    });

```

});

Any help will be appreciated. Thanks!

# Answer
> 2 votes
You can't trust JsFiddle when it comes to running Javascript in Drupal, because Drupal uses the Immediately Invoked Function Expression (IIFE), a well known pattern in JS. Raw code you supply the fiddle with may not always work in the application.

See managing JS in Drupal. Your code needs to be wrapped first. My guess? You have console errors regarding `$ is undefined`.

```
(function ($, Drupal) {
  Drupal.behaviors.myCustomBehavior = {
    attach: function (context, settings) {
      $(".cal-full").mouseover(function() {

        $(this).siblings('.cal-events-tooltip').addClass('cal-events-tooltip_show');
    $(this).siblings('.cal-events-tooltip').removeClass('cal-events-tooltip_hide');

    });

$(".cal-full").mouseout(function() {

        $(this).siblings('.cal-events-tooltip').removeClass('cal-events-tooltip_show');
    $(this).siblings('.cal-events-tooltip').addClass('cal-events-tooltip_hide');

    });
    });
    }
  };
})(jQuery, Drupal);

```

If this is Drupal 8, you will also need to require jQuery and related dependencies from your module or theme, so they are attached to the page before your script.

---
Tags: theming, javascript
---


# Question
Title: Add a graphic element in content type without modifying the .tpl
I would like to add a "like" icon at the end of articles. It’s just an icon which allow the reader of the article to click on the icon and increment a counter. It’s not a social button.

For now, i can add this icon directly in page.tpl

```
<?php print render($page['content']); ?>

<p class="like-article-container"><span class="like-article"><span class="glyphicon glyphicon-thumbs-up" aria-hidden="true"></span></span></p>

```

It works but i was wondering if it was possible to add it directly in the content type "article" in admin without modifying the file.tpl

# Answer
You can modify it in a preprocess\_page\_hook, in template.php file... but I would recommend you to stick with the tpl file approach, as you've done it there.
> 1 votes

---
Tags: 7, theming, nodes
---


# Question
Title: How to configure Node Export to mass node export?
I'm trying out Node Export for mass node export, but it seems that I have to choose every node to export individually.

What if I want to export all nodes of a selected content type? Is there any way I can do this in Node Export, or I should find another module?

# Answer
> 26 votes
You can do it with drush:

```
$ drush help ne-export
Export nodes using Node export.

Arguments:
  nids : A list of space-separated node IDs to export.

Options:
  --file : The filename of the output file.  If supplied, the node code will be
exported to that file, otherwise it will export to stdout.
  --format : If supplied, node code will be output using a particular export
format, if available. (e.g. serialize)
  --status : Filter for 'status'; A boolean value (0 or 1) indicating whether
the node is published (visible to non-administrators).
  --promote : Filter for 'promote'; A boolean value (0 or 1) indicating whether
the node should be displayed on the front page.
  --sticky : Filter for 'sticky'; A boolean value (0 or 1) indicating whether
the node should be displayed at the top of lists in which it appears.
  --translate : Filter for 'translate'; A boolean value (0 or 1) indicating
whether the node translation needs to be updated.
  --language : Filter for 'language'; The language code (e.g. de or en-US) of
this node.
  --type : Filter for 'type'; The machine-readable name (e.g. story or page) of
the type of this node.
  --sql : Filter by SQL (EXPERIMENTAL); An SQL query string that returns nids
(e.g. "SELECT nid FROM nodes WHERE nid < 10").
  --code : Filter by PHP code (EXPERIMENTAL); PHP code that prints or returns,
an array or CSV string of nids (e.g. "custom_get_my_nids();"). Don't include PHP
tags.

```

For example,

```
drush ne-export --type=article --file=article.txt

```

will output all of the article nodes to article.txt in serialized format. You can then use drush to import them:

```
$ drush help ne-import
Import nodes previously exported with Node export.

Arguments:

Options:
  --uid : User ID of user to save nodes as. If not given will use the user with
an ID of 1. You may specify 0 for the Anonymous user.
  --file : The filename of the input file.  If supplied, the node code will be
imported from that file, otherwise it will import to stdin.

```

For example:

`drush ne-import --uid=1 --file=article.txt`

\*updated

# Answer
> 5 votes
You could go to the list of all content in Drupal's admin pages ( /admin/content in D7), then filter by content type, then select all, then select 'Node export' from the dropdown menu

# Answer
> 0 votes
You can use Node export module for above mentioned purpose. It says:

> It allows users to export nodes and then import it into another Drupal installation, or on the same site. Using this module you can save yourself a lot of time setting up new websites that have similar nodes to websites you've already made, migrating nodes to new Drupal versions, or between development/staging/production sites.

# Answer
> 0 votes
This might help you in dividing the results. Simple bash script:

```
#!/bin/bash
# Run this script in Drupal root app directory!
# Requirements: drush command tool installed with ne-export command (you need Node Export module installed in Drupal)

maxRows=100
startFrom=0
for i in {0..17}
do
  startFrom=$(( (i)*100 ))
  echo "SELECT nid FROM node where node.type='noticia' limit $startFrom,$maxRows" # just for debugging
  drush ne-export  --file="nodes-exported/nodes-exported-$i.json" --format='json' --sql="SELECT nid FROM node where node.type='noticia' limit $startFrom,$maxRows" # of course set your own SQL here
done

exit 0

```

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


# Question
Title: Custom region twig template for region into node twig template
I did add a custom region to my theme via my .info.yml file :

```
regions:
  node_col_1: 'Bloc pour colonne 1'

```

and in my .theme file to make it available for node template:

```
function starterpf_d8_preprocess_node(&$variables) {
  // Allowed view modes
  $view_mode = $variables['view_mode']; // Retrieve view mode
  $allowed_view_modes = ['full']; // Array of allowed view modes (for performance so as to not execute on unneeded nodes)

  // If view mode is in allowed view modes list, pass to starterpf_d8_add_regions_to_node()
  if(in_array($view_mode, $allowed_view_modes)) {
    // Allowed regions (for performance so as to not execute for unneeded region)
    // Liste des régions utilisées directement dans les node.html.twig
    $allowed_regions = [
      'pole_col1','pole_col2','pole_col3','pole_col4',
      'node_col_1','node_col_2','node_col_3','node_col_4','node_col_5',
      'revue_presse','sortie_action','actuAssociation','projets','intervenants'
      ];
    starterpf_d8_add_regions_to_node($allowed_regions, $variables);
  }
}

/**
* THEME_add_regions_to_node
*/

function starterpf_d8_add_regions_to_node($allowed_regions, &$variables) {
  // Retrieve active theme
  $theme = \Drupal::theme()->getActiveTheme()->getName();

  // Retrieve theme regions
  $available_regions = system_region_list($theme, 'REGIONS_ALL');

  // Validate allowed regions with available regions
  $regions = array_intersect(array_keys($available_regions), $allowed_regions);

  // For each region
  foreach ($regions as $key => $region) {

    // Load region blocks
    $blocks = entity_load_multiple_by_properties('block', array('theme' => $theme, 'region' => $region));

    // Sort ‘em
    uasort($blocks, 'Drupal\block\Entity\Block::sort');

    // Capture viewable blocks and their settings to $build
    $build = array();
    foreach ($blocks as $key => $block) {
      if ($block->access('view')) {
        $build[$key] = entity_view($block, 'block');
      }
    }

    // Add build to region
    $variables[$region] = $build;
  }
}

```

Then I try to apply a custom template for this region but it seem not to work,and twig doesn't provide suggestions like for block,field,etc.. My file is called : region--node\_col\_1.html.twig His content:

```
{%
  set classes = [
    'region',
    'region-' ~ region|clean_class,
  ]
%}
{% if content %}
  <div{{ attributes.addClass(classes) }}>
    {{ content }}
  </div>
{% endif %}

```

What do I miss ? Thanks for help

EDIT: After test, template suggestion work for custom region added to `page.html.twig` but not for region added to a `node.html.twig`...folder structure seem not to be the way,most probably a hook in `.theme` file.

EDIT : someone could help me for the theme\_suggestions\_block\_alter ?

# Answer
I think your filename is incorrect. It should be:

`region--node-col-1.html.twig`.

Enable twig debugging to see the suggestions output in the HTML source, which will paint a better picture of what Drupal is expecting to see as template overrides.
> 2 votes

# Answer
According to your previous example, you are making the region available in the **node templates** as in this guide: https://atendesigngroup.com/blog/making-region-content-available-node-templates-drupal-8

You can find a guide for the templates of the node here:

> node--nodeid--viewmode.html.twig
> node--nodeid.html.twig
> node--type--viewmode.html.twig
> node--type.html.twig
> node--viewmode.html.twig node.html.twig
> 0 votes

---
Tags: 8, theming
---


# Question
Title: String translations not working after setting language in page preprocess function
I am using the domains module (D6) with multiple domains on a 1 site, and we have multiple languages on 1 domain. (We have to have this set up with no other option). Internationalization string translations is enabled and the translated strings in the t() function are in the database.

The domian language setting overrides the node language setting which causes the string translations not to work when having multiple languages on 1 domain.

I have overridden the domain language setting with the node language setting in the theme template\_preprocess\_page() function and works well but I think it happens too late in the process as the string translations still don't work.

What do I need to do to get the string translations to work?

```
function phptemplate_preprocess_page(&$vars, $hook) {
  global $language;

  // Reset Language to Page Node Level
  // Get the list of languages
  $languages = language_list();

  // Set up the new language code
  $new_lang_code = $vars['node']->language;

  // Make sure the required language object is actually set
  if (isset($languages[$new_lang_code])) {

    // Overwrite the global language object
    $language = $languages[$new_lang_code];
  }
  var_dump($language) // $language = node language setting
}

```

# Answer
> 0 votes
I have got this working now by moving the code into the preprocess\_node() function instead.

function phptemplate_preprocess_node(&$vars, $hook) {

  global $language;

  $languages = language_list();

  $new_lang_code = $vars['node']->language;

```
 if (isset($languages[$new_lang_code])) {
  $language = $languages[$new_lang_code];
 }
}

```

---
Tags: 6, i18n-l10n
---


# Question
Title: Get User's other field instead of Username,in the View?
I have one content type called "Test".In that content type i have Entity Reference field Referencing to Users called "field\_authors"\[**can have more than one user**\] . I have created a view of this type.Here while showing 'field\_authors' , it is showing User username, but Instead of username ,i want to show other field value of the User. How can i achieve this? Can anybody please help me? Drupal version:8.2.0
**Details:**
Currently View table column Output is: CC111,CC112,CC113 \[which are the usernames of different users in the site\]
I need user's other fields like "First name" instead of username in above Case.
I tried adding Relationship '(author) field\_authors' and Added field in view Table 'field\_authors'\[selected use relationship\] , But still output is CC111,CC112,CC113 etc instead of comma separated names.
I Got partial output after adding Relationship to that field,but since it is a multi field,output is coming in 3 different rows.Instead of it I need output in one row comma separated values.\[Ex:Name1,Name2,Name3\]

# Answer
> 1 votes
In order to use fields of user, you have to add a relationship (panel to the right, under contextual filter). Create a relation to the user entity.

---
Tags: 8, users, views
---


# Question
Title: Set number of values for a field in an entityform type based on a fixed value
I'm working with an entityform type that has a field with unlimited input values, so with the default button "Add another" I can add multple values for a field.

I'd like to fix this number of values, maybe with a get or post value, so I can preselect a specific number of values and then limit user to fill a specific number of fields.

Example: first select how many items to order --\> user selects 4 items --\> user must fill 4 values of the same field and user can't add more or less then 4 items.

Do you think it's possible with drupal modules?

# Answer
> 0 votes
After hours of searches I found a solution: https://www.drupal.org/node/2868353

---
Tags: forms, entities
---