title: Unique HTML ID's that are not necessary

text:
# Question
Title: Unique HTML ID's that are not necessary
I am new to Drupal and have encountered a weird issue. When using `drupal_render(drupal_get_form('user_register_form'))`, it is using HTML ID's like `edit-name--6` and `edit-mail--2` for the username and email fields. The thing is there is no other `edit-mail` or `edit-name` in the page.

There is old code that was targeting `edit-name` and `edit-mail` with JavaScript. How can I get it back to outputting just `edit-...` without the dashes and numbers? Or how can I specify a custom HTML ID for those fields?

# Answer
> 0 votes
If I were to guess, these elements are form elements for fields that can potentially hold a several (or even an unlimited number of) values. Or they've been built using Drupal's AJAX API, like this example...

`$form['input'] = [
 '#type' => 'textfield',
 '#title' => 'A Textfield',
 '#description' => 'Enter a number to be validated via ajax.',
 '#size' => '60',
 '#maxlength' => '10',
 '#required' => TRUE,
 '#ajax' => [
 'callback' => 'Drupal\d8_module\Form\ExampleForm::sayHello',
 'event' => 'keyup',
 'wrapper' => 'edit-output',
 'progress' => [
 'type' => 'throbber',
 'message' => t('Verifying entry...'),
 ],
 ],
];`

When an element on a page has been built with Drupal's built-in AJAX handling, an ID to target (the 'wrapper' value) is specified. This entire element gets swapped out with a new one but the id is modified by adding incrementing numbers to the end.

You can't really prevent this juggling; it's part of the Drupal AJAX implementation. If you need to target those items with CSS or Javascript, the recommended approach would be to use (or add) other attributes that don't change. Classes are an easy option, but you could also use any other consistent attribute.

---
Tags: forms
---


# Question
Title: How to enable modules through configuration?
I am trying to enable modules by adding them to `core.extension.yml` file without getting involved with Features, Configuration Installer or similar modules or profiles. The modules are enabled but their default configuration under `module_folder/config/install` or `module_folder/config/optional` are not imported. Is there a way to do this?

# Answer
> 4 votes
This will not works because you are only saying to Drupal that your module is installed, but when you install a module there are other process that need to runs to import the configs and execute the .install functions.

But you can create a new module that will install all the other modules, create a .install file and add this inside:

```
/**
 * Implements hook_install().
 */
function MY_MODULE_install() {
  $modules_list = [
    'nbsp',
    'typogrify',
    'other_module',
  ];
  \Drupal::service('module_installer')->install($modules_list);
  drupal_flush_all_caches();
}

```

And then you only need to install this module that will install all the other modules.

# Answer
> 4 votes
A possible alternative would be use the dependencies section of a module's mymod.info.yml description. Enabling the module will enable the dependencies.

```
name: My Module
description: Provides something great
core: 8.x
type: module
dependencies:
  - views

```

If you need to make sure that certain modules are enabled due to code changes in an existing module, then use update system. E.g. add a hook\_update\_N function to the mymod.install file that calls the module.installer service.

```
/**
 * Install file module.
 */
function mymod_update_8001() {
  \Drupal::service('module_installer')->install(['file']);
}

```

FYI - Trying to install an installed module will not cause problems.

Trying to go outside the normal system by accessing the core.extensions is probably not a long term maintainable option.

---
Tags: 8, installation, configuration, installation-profiles
---


# Question
Title: How to show taxonomy terms' description field on a node/add form instead of term title only in drupal 7?
I find it a bit disturbing that you cannot set which fields of taxonomy terms are displayed when you add a new node and have the terms listed.

There will be a bunch of terms which the user has to select one from. However, sometimes only showing a terms title wont be enough, so I'd like to also show a terms description when adding a new node.

How can you do that?

# Answer
The following solution slightly alters your requirement. Instead of having the term description field showing up as part of the term select widget, create a view block set to be visible on node/add pages which provides a table listing of each term and its description field.

To do this, create a new view of type "Taxonomy." It will have two fields: taxonomy term, and taxonomy term definition.

You could put help text associated with term\_reference field which alerts the user to the block which holds the terms and description.

It would be very difficult to alter any select widget to include the description field in a way that wouldn't make a mess of the page.
> 2 votes

# Answer
To show the taxonomy description instead of the name on a single node page you can use this in your theme template.php file:

```
function mytheme_preprocess_field(&$variables) {
  if ($variables['element']['#field_name'] == 'field_taxonomyfieldname') {
    if (isset($variables['element']['#items'][0]['taxonomy_term']->description)) {
      $variables['items'][0]['#markup'] = $variables['element']['#items'][0]['taxonomy_term']->description;
    }
  }
}

```

Making sure to change mytheme, field\_taxonomyfieldname to your own theme and field names and then clear Drupal caches before testing.
> 2 votes

# Answer
You can use the term reference tree module, this gives you a taxonomy term theme function. Create a subtheme of seven and override the theme function in template.php. In the example below I am also using the tipsy module, which converts the .tipsy class into a tooltip, so the taxonomy term description appears after clicking or hovering on the tooltip on the node add form, but you could of course also just print the $description.

```
/**
 * This function prints a single item in the tree, followed by that item's children
 * (which may be another checkbox_tree_level).
 */
function seven_subtheme_checkbox_tree_item($variables) {
    $element = $variables['element'];
    $children = element_children($element);
    $output = "";

    $sm = $element['#level_start_minimized'] ? ' term-reference-tree-collapsed' : '';

    if (is_array($children) && count($children) > 1) {
      $output .= "<div class='term-reference-tree-button$sm'></div>";
    }
    elseif (!$element['#leaves_only']) {
      $output .= "<div class='no-term-reference-tree-button'></div>";
    }

    foreach ($children as $child) {
      // $child is the tid
      $term = taxonomy_term_load($child);
      $description = trim(strip_tags($term->description));
      if (!empty($description)) {
        $tooltip = l('ⓘ', '#', array(
          'attributes' => array(
            'class' => array('tipsy'),
            'title' => $description,
          )
        ));
      }
      $output .= drupal_render($element[$child]) . $tooltip;
    }

    return $output;
}

```
> 0 votes

# Answer
a possible solution that you can loop through each item and get the description next to the term name.
> -1 votes

---
Tags: taxonomy-terms, entities, nodes
---


# Question
Title: Why do form builders have a $form parameter?
In Drupal 8, the first parameter of `FormInterface::buildForm()` is `$form`.

When implementing a form builder, one has the option of either adding stuff to this existing array and returning it, or creating a new $form array, discarding what was passed into the function. In my experience, both of these options usually work fine.

What's the point? Is there ever a case when this parameter is needed?

I think to vaguely remember that this is somehow relevant when a form is rebuilt, so this would be the old form.. but I would not really know what to do with it.

# Answer
Its an interesting question as there are now two ways of altering forms.

Using HOOK\_form\_alter ie book\_form\_node\_form\_alter with $form **by ref** and by *inheritance* **returning** $form as done in ie \Drupal\forum\Form\Overview::buildForm

```
class Overview extends OverviewTerms {
  ...
  public function buildForm(array $form, FormStateInterface $form_state) {
    ...
    $form = parent::buildForm($form, $form_state, $vocabulary);
    ...
    return $form;
  }
  ...
}

```

where \Drupal\taxonomy\Form\OverviewTerms::buildForm gets called using **$form = parent::buildForm($form, $form\_state, $vocabulary);** thus in fact zapping $form.

Most code seems to **return parent::buildForm($form, $form\_state, ...);** which we could call 'method' 3.

I guess hook\_form\_alter will disappear in the next version (10.x?) in favour of event listeners
> 1 votes

---
Tags: 8, forms
---


# Question
Title: Generate content format for mult items within view
**What I'm trying to do**

Create a View that looks similar to this, but with multiple titles, each which represents a "Team":

So you can imagine a page where multiple teams are listed, each with a `Title` and a `Description` and an image for each team member (which links to their profile).

**How would you accomplish this?**

**What I've thought to do so far** So far, I thought that I could create a Content Type with these fields:

* Title
* Description
* Image (unlimited)
* Name (unlimited)
* Link (unlimited)

Then I thought I could create a View and use custom text, but that didn't work because it renders per field (if that makes sense). So, if I put `<a href='[field_url]'>[field_image]</a>`, it prints out `<a href='url1,url2'>img1,img2</a>`.

I assume there's a way to do this that I'm just not thinking of.

# Answer
What you need is multiple 'rows' for team members. to accomplish this with your configuration you could uncheck **Display all values in the same row** for your image, name and link field.

It is better to use a module for your grouped fields like paragraphs module.
> 0 votes

---
Tags: views
---


title: How do I correctly use jQuery once()?

text:
# Question
Title: How do I correctly use jQuery once()?
Due to a module, the Drupal behavior I implemented is called five times instead of once.

```
(function ($) {
  Drupal.behaviors.myFunction = {
    attach: function (context, settings) {
      // …
    }
  };
})(jQuery);

```

How do I correctly use jQuery `once()`?

# Answer
> 27 votes
You can use `$.once()`, which is available in both Drupal 7 and Drupal 8. The code called inside `$.once()` will only be executed a single time for the HTML element it is called on.

For Drupal 7, you can do this.

```
(function ($, Drupal) {

  function someElementWatcher(context) {
    // $.once acts like $.each, and loops through the found elements.
    // The code inside $.once() will act on each element in the jQuery object
    // a single time.
    $(context).find(".some_element").once("some-arbitrary-but-unique-key", function () {
      // $(this) refers to the current instance of $(".some_element")
      $(this).click(function () {
        // Do something clicky.
      });
    });
  }

  Drupal.behaviors.someUniqueKey = {
    attach:function (context) {
      someElementWatcher();
    }
  };
}(jQuery, Drupal));

```

In Drupal 8, the `$.once()` functionality has changed under the hood, and the method of setting it has changed on the front end. In Drupal 8, `$.once()` needs to be combined with `$.each()`. You need to change the following part.

```
$(context).find(".some_element").once("some-arbitrary-but-unique-key", function () {});

```

Instead, you need to use this.

```
$(context).find(".some_element").once("some-arbitrary-but-unique-key").each(function () {});

```

In Drupal 9, `once()` stopped to be a jQuery function. To use `once()` library, first add *core/once* as dependency of the relevant library in the .libraries.yml file.

```
some_library:
  css:
    ...
  js:
    ...
  dependencies:
    - core/once

```

You can now use `once()` to retrieve a list of elements and loop through them.

```
const elements = $(context).find(".some_element").once("some-arbitrary-but-unique-key");
elements.each(function () {
  // Do something with the current element.
});

```

# Answer
> 6 votes
Drupal provides the jquery plugin `once()`, which allows you to ensure a function is run only once on any single element. You can use this within your behaviour.

See *Drupal.behaviours* here: https://www.drupal.org/docs/8/api/javascript-api/javascript-api-overview

---
Tags: javascript
---


# Question
Title: Display specific service under ShareThis button
I went through the configuration of ShareThis module but couldn't find any way to hide/disable services which aren't required. In my case I am using the ShareThis button under "Selected Service"as per my site design. This button displays the list of all the available services but what if I just wanted to display few required services like Facebook, Twitter, LinkedIn, Youtube & Whatsapp.

# Answer
> 0 votes
Instead of using ShareThis module which is too difficult to modify. I used AddToAny module which provides me with only the required services. To provide it a layout I created a twig file for the services block and add whatever HTML & Classes I wanted to use.

I displayed the services in a modal window.What I wrote in twig file:

```
{% block content %}
<div aria-labelledby="myModalLabel" class="modal fade" id="modal-external-link" role="dialog" tabindex="-1">
<div class="modal-dialog modal-sm" role="document">
<div class="modal-content">
<div class="modal-header"><button aria-label="Close" class="close" data-dismiss="modal" type="button"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Share
</h4>
</div>
<div class="modal-body">  {{ content }} </div>
</div>
</div>
</div>
{% endblock %}

```

Before Somebody asks me why I didn't do it with ShareThis. I didn't because AddToAny is lightweight.

---
Tags: social-network
---


# Question
Title: Does trusted_host_patterns support sub-directories?
My site is installed in a sub-directory:

```
http://example.com/cms

```

When I define `trusted_host_patterns`, the following is OK:

```
$settings['trusted_host_patterns'] = array(
  '^example\.com$',
);

```

However, I cannot enforce the *host pattern* with a sub-directory, i.e.:

```
$settings['trusted_host_patterns'] = array(
  '^example\.com/cms$',
);

```

Does `trusted_host_patterns` support sub-directories?

# Answer
Those patterns are used to check the host passed in the headers, so they cannot contain a subdirectory, since that is not passed as host. See the code in Request::getHost().

```
public function getHost()
 {
  if ($this->isFromTrustedProxy() && self::$trustedHeaders[self::HEADER_CLIENT_HOST] && $host = $this->headers->get(self::$trustedHeaders[self::HEADER_CLIENT_HOST])) {
    $elements = explode(',', $host);

    $host = $elements[count($elements) - 1];
  }
  elseif (!$host = $this->headers->get('HOST')) {
    if (!$host = $this->server->get('SERVER_NAME')) {
      $host = $this->server->get('SERVER_ADDR', '');
    }
  }

  // trim and remove port number from host
  // host is lowercase as per RFC 952/2181
  $host = strtolower(preg_replace('/:\d+$/', '', trim($host)));

  // as the host can come from the user (HTTP_HOST and depending on the configuration, SERVER_NAME too can come from the user)
  // check that it does not contain forbidden characters (see RFC 952 and RFC 2181)
  // use preg_replace() instead of preg_match() to prevent DoS attacks with long host names
  if ($host && '' !== preg_replace('/(?:^\[)?[a-zA-Z0-9-:\]_]+\.?/', '', $host)) {
    throw new \UnexpectedValueException(sprintf('Invalid Host "%s"', $host));
  }

  if (count(self::$trustedHostPatterns) > 0) {
    // to avoid host header injection attacks, you should provide a list of trusted host patterns

    if (in_array($host, self::$trustedHosts)) {
      return $host;
    }

    foreach (self::$trustedHostPatterns as $pattern) {
      if (preg_match($pattern, $host)) {
        self::$trustedHosts[] = $host;

        return $host;
      }
    }

    throw new \UnexpectedValueException(sprintf('Untrusted Host "%s"', $host));
  }

  return $host;
}

```
> 2 votes

# Answer
I think this will help you.

```
$settings['trusted_host_patterns'] = array(
 '^yourdomain\.com$',
 '^www\.yourdomain\.com$',
);
if (file_exists(__DIR__ . '/settings.local.php')) {
}

```

Wish you best of luck, this is working fine for me.
> 0 votes

---
Tags: 8
---


title: Description field for file field

text:
# Question
Title: Description field for file field
I have a file field in a content type. I have enabled the description field for this field. How can I print this description field in twig???

I have a situation here I need to print description field only for one content in views page instead of all the contents on the same page.

For example: First content has **Download**
Second content has **Download**
Third content has **field description**

Can I put some condition in twig or views field?

# Answer
To use the description field directly in twig I found an easier way. Simply add the file field in Views, then rewrite the results and add the token for description and file. Now you can use the field directly into twig file.

Otherwise You might have to do good use of Kint or DSM to find out where does description field come up.
> 0 votes

---
Tags: views
---


# Question
Title: Drupal custom node type add field to relate content
I was wondering if it's possible to create a custom node type with a custom field to relate it to another node content(same or diferent node type). And then in my node--customtype.tpl display the fields(render($content\['myfield'\])) of the custom node type but also to display all the fields of the related node and I want to do it programmatically.

I've been searching, and I found a module called References, but there's no documentation about how to use it exactly.

The other option that I thought is to add a int field to fill with the nid of the related content, but I don't know if it's possible to generate a query with that nid and append it to the $content\['extrafield'\] and render it on my node--customtype.tpl

But here you are the experts and I hope you can guide me with the correct way to do it.

# Answer
> 0 votes
I found the answer, there's a module named Entity references, this allows you to add and Entity Field in your custom node type, and with this you can relate to another contents. To use it you just need to add the field, select what do you want to point to, an that's all. To render the entity field and it's fields you need to add to you tpl something this:

```
<?php print render($content['field_myentityfield'][0]['node'][62]['fieldof_entityfield']['#items'][0]['value']); ?>

```

You can check it with devel.

---
Tags: 7, nodes
---


title: How to override theme_file_widget?

text:
# Question
Title: How to override theme_file_widget?
Is there any method to override this function `theme_file_widget`.

I tried to to do the following in my module.

`function mymodule_file_widget($variables)`

and also in my theme

`function mytheme_file_widget($variables)`

but did not work. I cleared the cache also. Is there any method to override this function?

# Answer
The correct way to override the theme function is:

```
/**
 * Implements hook_theme_registry_alter().
 */
function mymodule_theme_registry_alter(&$theme_registry) {
  $theme_registry['file_widget']['function'] = 'mymodule_file_widget';
}

function mymodule_file_widget($variables) {
 //your code
}

```
> 0 votes

---
Tags: 7, theming
---


title: Geolocation Click Marker Event

text:
# Question
Title: Geolocation Click Marker Event
I'm using a Geolocation Fields View with Drupal 8 and need to manipulate the Style of the Marker Info Window. there is no class to style the pop-Up-window for the Info Text. The Info Text has a class named gm-style-iw. I would like to do this:

```
var popupcontent = $('.gm-style-iw');
popupcontent.parent().addClass('gmap-popup');

```

But I can't get the right event. I can get the Click on Map Event with this:

```
   if (typeof Drupal.geolocation !== 'undefined') {
     Drupal.geolocation.googleCallbacks.push({'callback' : function () {
        Drupal.geolocation.maps[0].googleMap.addListener('click', function() {
        console.log('Clicked on the map.');
        });
     }});
    }

```

But I need to get the Click on Marker Event. I can not figure out the Marker Objekt and the right syntax for the click event.

# Answer
> 0 votes
Try this:

```
if (typeof Drupal.geolocation !== 'undefined') {
            Drupal.geolocation.googleCallbacks.push({'callback' : function () {
                Drupal.geolocation.maps[0].googleMap.addListener('tilesloaded', function() {
                    $('.geolocation-common-map').on('click', function() {
                        console.log('Clicked on the map.');
                    });
                });
            }});
        }

```

---
Tags: 8, google-maps
---


title: Compare views.total_rows in twig file

text:
# Question
Title: Compare views.total_rows in twig file
Original Code:

```
<div class="our-story search-query">
  <div class="container">
  <h1>Search Results</h1>
  {% if keysearch %}
  <p>{{ view.total_rows }} results found for '<span class="font-500">{{ keysearch }}</span>'</p>
  {% endif %}
  </div>
  </div>

```

I have this code in a twig file. I need to put in a condition:
1. If search results are ZERO, then it should say "No results found for 'YYY' "
2. If results are found i.e above Zero, then it should say " XX results found for 'YYY' "

Code with If condition:

```
{% if keysearch %}
  {% set variable = {{ view.total_rows }} %}
  {% if variable > 0 %}
  <p>{{ view.total_rows }} results found for '<span class="font-500">{{ keysearch }}</span>'</p>
else {
 <p>No results found for '<span class="font-500">{{ keysearch }}</span>'</p>
}
  {% endif %}

```

When I put in a condition under \`{% if keysearch %} it throws an error:

Twig\_Error\_Syntax: A hash key must be a quoted string, a number, a name, or an expression enclosed in parentheses (unexpected token "punctuation" of value "{" in "themes/custom/iifl/templates/views/views-view--search-page.html.twig" at line 59. in Twig\_ExpressionParser-\>parseHashExpression() (line 281 of vendor\twig\twig\lib\Twig\ExpressionParser.php).

Can someone help me out.

# Answer
```
    {% if keysearch %}
  {% set variable = {{ view.total_rows }} %}
  {% if variable > 0 %}
  <p>{{ view.total_rows }} results found for '<span class="font-500">{{ keysearch }}</span>'</p>
{% else %}
 <p>No results found for '<span class="font-500">{{ keysearch }}</span>'</p>
  {% endif %}

```

Do not know if this is the case , but your else condition is not twig like.
> 0 votes

---
Tags: views, theming, search
---


# Question
Title: How do I reset all user passwords to 123 with drush or SQL?
For testing purposes I like to reset all user passwords to 123.

Is this possible in Drush or SQL? I guess the query will be someting like this but cannot find the exact yourhash:

```
UPDATE `<mydatabase>`.`users` SET `pass` = '<yourhash>' ;

```

Can I run the final query with drush?

# Answer
Yes, you can do this using Drush, with following steps (e.g.):

1.Generate a password hash using following command:

```
$ cd [/var/www/html/drupal7]
$ php scripts/password-hash.sh '123'

```

2.Now run following drush command:

```
$ drush sql-cli
mysql > UPDATE users SET `pass` = 'pasted_big_hash_from_above' WHERE uid > 1;

```

Update `pasted_big_hash_from_above` with password hash generated using `php` command in step #1.
> 2 votes

# Answer
Solved.

Query can be done in Drush with:

```
drush sql-query UPDATE `users` SET `pass` = '$S$DM7xrCBIKOrShBhgb1eUkpPlnnAq36QKIlMfdkKhvaTS2iv0PuJ3'

```
> -2 votes

---
Tags: 7, drush
---


title: Filter results using taxonomy terms

text:
# Question
Title: Filter results using taxonomy terms
I have an index for a content type that has a taxonomy field attached.

I have a fulltext search up and running using the index, but would like to be able to filter the results additionally using tags.

If I add the taxonomy field to the index, it is added as an integer value, and the ID of the tag assigned is being indexed in Solr.

If, however, I try to add the field as a filter in my View, I get an error that there is no handler available.

What is the correct way to implement filtering by taxonomy term?

# Answer
> 0 votes
IMHO the best way is to add the taxonomy's name to the index. This may not be shown as an option in D7 if you have not asked for the fields to be extended to the referenced entities.

Note: expanding the field list in D7 can make the field list take *Minutes* to load and you may get a few script running long warnings. Be patient and let the script keep running. The list will come up eventually.

Once you have the text in the index, you can use this in either the search view filter or use it in a facet.

An alternative would be to add a relationship between your term id search field to the actual term data. Then you should have the term name available for use.

Note that this method will add a lot more overhead to your search than just having the term names in the index.

---
Tags: 8, search
---


# Question
Title: Why does JsonResponse keep returning a <?php tag at the beginning?
I am returning my data like this:

```
return new JsonResponse([
  'data' => $this->data,
  'error' => $this->error,
  'errorMsg' => $this->errorMsg,
], 200);

```

Somehow, a PHP opening tag is always being added, making it impossible for Angular 2 to parse the result.

```
<?php{"data":[],"error":true,"errorMsg":"This email seems to be used by another user."}

```

I have already tried the most desperate solutions like `str_replace()` in Response.php in Drupal but it did not seem to help.

Why is it happening?

# Answer
I was having trouble with this same bug.

At the top of my response there was a php short open tag

```
<?
<aside data-entity-id="392" data-entity-type="node" class="sidenote">

```

That was breaking my jQuery ajax call.

It was working locally but broken on the QA server. Ultimately, after researching the problem, I knew that there was some corrupt PHP file outputting to the page before Drupal explicitly output the page.

After discovering from my php.ini file that short tags were disabled on QA and enabled locally, I was able to grep the codebase for documents in my theme and custom modules that started with a php short tag. Sure enough, my theme's .theme file was empty with just a php short open tag in it:

```
<?

```

Changing this to a regular php open tag and a newline fixed the bug.

```
<aside data-entity-id="392" data-entity-type="node" class="sidenote">

```

The qa server was outputting this to the page, but only on this one page (that I know about). I guess because I was calling

```
\Drupal::service('renderer')->renderRoot($data);

```

If I removed that, the controller could return clean json or output. But when I got the theme layer involved, the bug crept up.
> 0 votes

---
Tags: 8
---


title: Why can't I connect to my Solr server?

text:
# Question
Title: Why can't I connect to my Solr server?
I am attempting to configure Solr search with a drupal web page on a dev server. I have installed the server and the Search\_API\_Solr modules along with it's dependencies. When I try to connect the Search\_API\_Solr module to my server, I get the error:

> The Solr server could not be reached. Further data is therefore unavailable.
>
> **SOLR SERVER URI**: http:// host\_machine:8983/solr/#
>
> **CONNECTION**: The Solr server could not be reached. Further data is therefore unavailable.

To attempt to remedy this, I've tried linking directly to the core that I have setup (e.g. http://host\_machine:8983/solr/mycorename) to no success.

Does anyone have any experience fixing this? I've searched through every bug/support post I came across and attempted all of the solutions with no fix.

P.S. I've read somewhere that you can't access a Solr server if the Drupal site is running on the same host. I don't know the validity of that.

Any suggestions would be much appreciated, thanks.

# Answer
> 3 votes
It turns out that if you use the IP of your host machine, if you're hosting Solr and the Site on the same box, you can't use the IP of the box to connect. In my case, I was trying xx.xx.xx.xx:8983/solr/my\_core which was failing.

After changing the address to http://127.0.0.1:8983/solr/my\_core I am finally connected.

---
Tags: search
---


title: How to assign a new icon to a pager?

text:
# Question
Title: How to assign a new icon to a pager?
The current default pager in Views Paging Drupalgap is easily neglected.

>

Can I assign it a new icon or create my own pager button? Currently, what I know is to put it at the top or the bottom using `pager_pos: 'bottom'`, but nothing else.

# Answer
Thanks to Tyler. I follow his suggestion and have solved this by adding the theme\_pager\_link() to `app/themes/my_theme/my_theme.js`. Here is what I added:

```
function my_theme_pager_next(variables) {
  try {
    var html;
    variables.page = parseInt(variables.results.view.page) + 1;
    var link_vars = {
      text: 'Next Page',
      attributes: {
        'class': 'pager_next',
        'data-icon': 'fast-forward'
      }
    };
    html = theme_pager_link(variables, link_vars);
    return html;
  }
  catch (error) { console.log('my_theme_pager_next - ' + error); }
}

function my_theme_pager_previous(variables) {
  try {
    var html;
    variables.page = parseInt(variables.results.view.page) - 1;
    var link_vars = {
      text: 'Previous Page',
      attributes: {
        'class': 'pager_previous',
        'data-icon': 'fast-backward'
      }
    };
    html = theme_pager_link(variables, link_vars);
    return html;
  }
  catch (error) { console.log('my_theme_pager_previous - ' + error); }
}

```

now the pager become like this:
> 0 votes

---
Tags: paging, javascript
---


# Question
Title: Programmatically get webform submitted field values
How can i print/echo the submitted value of specific field in from a webform? I need to do this in the webform 2 PDF module so i can better customize the output of generated PDFs. Im fairly new to Drupal so an example of how to get a simple f\_name filed would be great.

I'd also like to start getting more involved with the Webform API too.

i.e

First Name: SUBMITTED NAME VALUE

# Answer
> 4 votes
To get webform values right after the page submit, they're stored in the global `$_POST` variable.

Alternatively you need to load the right webform submission.

### Drupal 7

Here is example how to do it in Drupal 7 (as per this post):

```
module_load_include('inc', 'webform', 'includes/webform.submissions');
$submissions = webform_get_submissions(array('nid'=> 123));

foreach ($submissions as $submission){
    foreach ($submission->data as $row=>$data){
        print '<pre>'; print_r($row); print '</pre>';
        print '<pre>'; print_r($data); print '</pre>';
    }
}

```

### Drupal 8

Here is the example to get the webform submission in Drupal 8:

```
$entity = \Drupal::entityTypeManager()->getStorage('webform')->load('my_webform');
$form = $entity->getSubmissionForm();
$elements = $form['elements'];

```

Here is the example using `drush`:

```
drush ev 'print_r(\Drupal::entityTypeManager()->getStorage("webform")->load("repairs_taps")->getSubmissionForm()["elements"]);'

```

# Answer
> 2 votes
In recent 3.x and 4.x versions of webform it has an hook based API to allow you do stuff with submitted webform values.

Look at like hook\_webform\_submission\_insert() or hook\_webform\_submission\_update() (if your webform has Drafts enabled for instance the final submission is an UPDATE call with isNew == False and isDraft == False).

The functions take a parameter `$submission` that is a PHP array of the submitted form values ... You can do whatever you want with them from there.

# Answer
> 1 votes
In Drupal 5-7 it looks like one can use the `webform_get_submissions` function.

# Answer
> 0 votes
**Drupal 8 solution**:

```
$entity = \Drupal::entityTypeManager()->getStorage('webform')->load('my_webform');
$form = $entity->getSubmissionForm();
$elements = $form['elements'];

```

At the moment there is no function webform\_get\_submissions() in Drupal 8 (as exists in D7 and D6). Above lines can help to get the submissions of a specific webform.

---
Tags: 7, webforms
---


title: Behat - Selenium failing

text:
# Question
Title: Behat - Selenium failing
I am trying to setup behat tests with Selenium and Chromedriver for my D8 project.

All @api tests work perfectly, but as soon as I add @javascript, it stops working with

```
Behat\Testwork\Call\Exception\FatalThrowableError: Fatal error: Call to a member function elements() on null in vendor/behat/mink-selenium2-driver/src/Selenium2Driver.php:488

```

My Behat.yml

```
default:
  suites:
    default:
      contexts:
        - FeatureContext
        - Drupal\DrupalExtension\Context\DrupalContext
        - Drupal\DrupalExtension\Context\MinkContext
        - Drupal\DrupalExtension\Context\MessageContext
        - Drupal\DrupalExtension\Context\DrushContext
 extensions:
   Behat\MinkExtension:
     goutte: ~
     javascript_session: 'selenium2'
     browser_name: 'chrome'
     selenium2:
       wd_host: 'http://192.168.56.1:5555/wd/hub'
     base_url: http://mydev.dev
   Drupal\DrupalExtension:
     api_driver: "drupal"
     blackbox: ~
     drush:
       root: "/usr/share/drush"
     drupal:
       drupal_root: "/var/www/mydev"

```

It is important to note that i am running inside a vagrant box and that I am also running my behat tests from within the vagrant box using:

```
bin/behat -v -c behat.yml features/my_feature/

```

My current feature just contains:

```
@api @javascript
Feature: Create a Quiz
In order to have a quiz on my site, as a Content Editor, I need to be
able to create one

Scenario: Create a quiz
  Given I am logged in as a user with the "administrator" role
  And I go to "node/add/quiz"
  #Then show last response

```

I have registered a node on my local machine (host) to the selenium hub within the vagrant. I have also validated that http://192.168.56.1:5555/wd/hub/ is working just fine.

Thanks in advance

# Answer
It turned out to be a bug in the Drupal extension that is fixed here: https://github.com/jhedstrom/drupalextension/pull/379
> 1 votes

---
Tags: 8, testing
---


title: Migrate as separate files

text:
# Question
Title: Migrate as separate files
**How can I create individual migration groups - one for each XLM file, without having to write a new migration class for each file?**

I have dozens of XML files waiting to be imported into Drupal using the Migrate module and API.

Currently, all my migrations are registered under a single group called *Questions* as shown below:  That single group of *222* imports represents 5/6 of my XML files. If I import the pending dozens of XML files, I will have upwards of 10,000 imports.

What I would rather have is each XML file having it's own individual group. That way I can revert a single XML file where necessary instead of all them.

Can anyone help me with this scenario?

# Answer
**Update**: this answer is probably fine for D8 but not D7.

Using the migrate\_plus module, I was able to specify shared configuration for about a dozen different feeds that needed to be given separate taxonomies upon import based on which organization's media I was importing. I created a group with my `source` and `process` configuration, then created individual importers for each feed with just the configuration that was specific to that feed. If I wanted to import them all at once I could run `drush mi --group=<group_name>`, and if I wanted to roll back a single feed I could run `drush migrate-rollback <migration_name>`. The only tedious part for me was creating a dozen nearly-identical migrations.

So, for example, here's a group definition for an Twitter importer:

```
id: twitter_importer
source_type: twitter
shared_configuration:
  source:
    plugin: url
    data_fetcher_plugin: http
    data_parser_plugin: json
    authentication:
      plugin: oauth2
      base_uri: 'https://api.twitter.com'
      token_url: /oauth2/token
      grant_type: client_credentials
    fields:
      -
        name: id
        selector: id_str
      -
        name: text
        selector: text
      -
        name: timestamp
        selector: created_at
    ids:
      id:
        type: string
  process:
    title:
      plugin: substr
      source: caption
      start: 0
      length: 254
    type:
      plugin: default_value
      default_value: twitter_feed_item
    # etc. etc.

```

Then a few migrations like this:

```
id: tw_dept_a
dependencies:
  - migrate
  - migrate_plus
migration_group: twitter_importer
source:
  # this changes from migration to migration
  urls: 'https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=tmountjr&count=10'
process:
  field_source:
    # this also changes; works because the group's shared config specifies the plugin
    default_value: tmountjr
destination:
  plugin: 'entity:node'

```

It's annoying setting it all up on the frontend but after the third one you get pretty quick at copy/pasting the template and replacing one or two variables.

So I guess to answer your question:

> How can I create individual migration groups - one for each XLM file, without having to write a new migration class for each file?

I'm not sure you can get around that...but you can abstract a lot of the repeated configuration out of each individual file using shared configurations. You can maybe further refine the process by having a template file with placeholder variables, duplicating the file, and using `sed` on the new file to replace filenames:

```
cp migration_template.yml migrate_plus.migration.migrate_xml1.yml
sed -i "s/filenameplaceholder/file1\.xml/g" migrate_plus.migration.migrate_xml1.yml

```
> 0 votes

# Answer
The answer to your question is to use `registerMigration` as described here: https://www.drupal.org/node/1824884

Once upon a time the D7 migration classes supported a `DynamicMigration` class which is now obsolete: https://www.drupal.org/node/2471206

But the idea is that per XML file you would do something like:

```
foreach ($xml_files as $file) {
  MigrationBase::registerMigration(
  'ExampleUserMigration',
  'ExampleUser',
   array(
      'group_name' => 'example',
      'default_uid' => 1,
      'my_source_file' => $file)
  );
}

```

And your migration would examine the passed in custom `my_source_file` migration argument and set the migration to use that specific file.

The above code could simply be a simple php script you call using Drush for example to "register" your migrations.

**EDIT**

Dynamic migrations are still supported somewhat in D8 via: https://www.drupal.org/docs/8/api/migrate-api/building-dynamic-migrations
> 0 votes

---
Tags: 7, migrations
---


# Question
Title: How to realize ajax on a form element with autocomplete
I have a form textfield element, which contains autocomplete feature using #autocomplete\_route\_name.

Could you clarify me, how to call ajax function when the textfield value has been set via autocomplete ? That is, for example, an user has selected a value from the autocomplete list, set it into the textbox and right away something should be executed via ajax depending on new value of the textbox.

Which ajax event should I use for it ?

# Answer
I managed to find the solution. My code works with an event "autocompleteselect".

Here's an example of code

```
$form['autocomplete_field'] = [
            '#type' => 'textfield',
            '#title' => t('Autocomplete search'),
            '#autocomplete_route_name' => 'autocomplete_route',
            '#ajax' => [
                'callback' => '::ajaxFunctionAfterAutocomplete',
                'event' => 'autocompleteselect',
            ]
        ];

```
> 0 votes

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


# Question
Title: Populating select list from a taxonomy term field
I'm trying to populate a select list dynamically by pulling its values from a taxonomy term field linked to the current-user account. Just to clarify, below function is a hook defined by a module that came with a custom installation profile. It is basically used to create fields on a specific form. So, my custom module has-

```
function some_function_attributes() {

      global $user;
      $user_fields = user_load($user->uid);
      $termid = $user_fields->field_user_organization['und']['0']['tid'];
      $taxonomy_term = taxonomy_term_load($termid);
      //dsm($taxonomy_term);
      $options = field_get_items('taxonomy_term', $taxonomy_term, 'field_org_environment','select');
      dsm($options);
      return array(
        'environment' => array(
        'type' => 'select',
        'options' => $options,
        'name' => t('Environment'),
        )
      );
    }

```

---

Allowed values in the field (for this user)-

E1|Env1

E2|Env2

---

Here's the devel screenshot for `dsm($options);`

So, its populating the right field but not in the way it should.

---

Actual form element looks like this-

Currently, its just returning the array and I can't figure out what I missed. Been banging my head to the wall for this- How would I populate Env1 and Env2 in this select-list ?

# Answer
> 0 votes
You'll have to reformat the `options` array to be in the form `'return value' => 'display value'`. See https://api.drupal.org/api/drupal/developer%21topics%21forms\_api\_reference.html/7.x#options

---
Tags: 7, forms
---


# Question
Title: How to create a scheduler for updating a boolean value using Rules?
I am displaying a boolean value as 'New' along with published content title.

Now I need like, the 'New' tag should be displayed for a period (ex: 3 months). After this period I need that content as it is, but 'New' tag should be removed.

# Answer
> 0 votes
It's defined in node.module like follows

```
define('NODE_NEW_LIMIT', REQUEST_TIME - 30 * 24 * 60 * 60);

```

AFAIK, you can't redefine this value. I think you need to change and use your value in all the places.

I'll check and If I found better option I'll update my answer :)

# Answer
> 0 votes
I'm assuming that your boolean variable used to display that "*Nieuw*" (= the Dutch for "New", right?) is actually implemented via a custom (boolean) field that you added to each relevant content type. Let's assume its machine name is `field_nieuw_ja_nee`. If my assumption is wrong, at least that's a way you could configure it also.

Based on that assumption, here is a blueprint of how to make it work:

### Step 1 - Create a Rules Component

* **Parameter**: a node (for the node to be processed).
* **Rules Action**: "set a data value", related to the `field_nieuw_ja_nee` field of the node, and set the value so that it matches with your requirement "new tag should be removed" (probably just set the boolean to 0).
* Use the Rules UI to **unit test** this Rules Component, by clicking on the "execute" link (to the right of the Rules Component), to be sure your Rules Component works as you want (and to avoid you have to wait for 3 months to see if it works as designed ...).

### Step 2 - Create a rule to schedule the Rules Component

* **Rules Event**: After saving a new node.
* **Rules Condition**: Check if the entity has field `field_nieuw_ja_nee` (we don't want to waste time on nodes that don't have such boolean field).
* **Rules Action**: Schedule the execution of a Rules Component from step 1, to have it executed "3 months after the node was saved".

---
Tags: entities, rules
---


# Question
Title: How add menu to my node programmatically?
This is how i create my node :

```
    $value= array(
                'type' => 'page',
                'title'=>"First node",
                'body' => array(
                    'value' => "test",
                    'format' => 'full_html',
                ),
);

$nodeEntity=\Drupal::entityTypeManager()
            ->getStorage('node')
            ->create($value);

        $nodeEntity->save();

```

This work fine.

But i try to give a menu parent to this node.

i try that :

```
$value= array(
            'type' => 'page',
            'title'=>"First node",
            'body' => array(
                'value' => "test",
                'format' => 'full_html',
            ),
            'menu'=>array(
             'title'=>"First node",
             'menu_parent'=>6,
             'description' => '',
             'enabled'=>1

        ),

```

);

i set the field menu because it's the name of the field in the node edit form. But for the nodeEntity, this field doesn't exist.

How can i give a parent menu id to my node ?

**UPDATE**

if i set menu\_link instead of menu, i got no error i still can't see the menu on the node.

# Answer
> 2 votes
After look into the database and some test, this is how i add a menu to my node on the creation or on node update :

For this example, i load a node :

```
  $nodeEntity=\Drupal::entityTypeManager()
            ->getStorage('node')
            ->load(312);

```

> After you create the link :

```
$menu_link = MenuLinkContent::create([
    'title' => 'name of your menu',
    'link' => ['uri' => 'internal:/node/' . $nodeEntity->id()],
    'menu_name' => 'main',
    'expanded' => TRUE,
]);

$menu_link->save();

```

If you want add a parent to your menu just add this in $menu\_link :

> $menu parent is the uuid of the parent menu

```
'parent' => 'menu_link_content:' . $menuParent,

```

> Then you need to update menu\_link\_content\_data

```
  $this->database->update('menu_link_content_data')
            ->fields([
                'link__uri' => 'entity:node/'.$nodeEntity->id(),
            ])
            ->condition('id', $menu_link->id())
            ->execute();

```

The link between the menu and the node is the link\__uri, you need to tell him to reference the entity node.

After that, you ll see your menu link on your node.

I haven't find better solution with Drupal API for now.

---
Tags: 8, nodes, navigation
---


# Question
Title: How to enable WYSIWYG in a text field summary?
I have a body field (Text field with summary) with WYSIWYG CKeditor enabled.

However, the "summary" part of the field lacks a WYSIWYG editor.
How can I enable it?

# Answer
The WYSIWYG module's logic acts on text fields with input formats, if you want to explicitly target a form element by its ID you can use the CKEditor module instead.
> 4 votes

# Answer
Under your content type -\> manage fields for the summary field you can enable text processing to be filtered text (user selects input format). Hope that helps.
> 2 votes

# Answer
I had created my own summary field in CCK. I use the CKeditor and this only worked after I realised I had to configure the field as a multiline text area and not as a single line text field.
> 2 votes

# Answer
I just tried WYSIWYG module version 7.x-2.x-dev with CKEditor (the editor, not the Drupal module), and it actually worked -- the summary field now displays with a wysiwyg editor instead of the plain textarea.
> 0 votes

# Answer
If you are using the wysiwyg module you can enable/disable this in the wysiwyg profile settings. It’s in the fieldset at the bottom: «Basic settings - Enable on summary fields».
> 0 votes

---
Tags: 7, entities, wysiwyg
---


title: Slideshow browse button doesn't work

text:
# Question
Title: Slideshow browse button doesn't work
I'm trying to setup a slideshow on my site using the Slideshow setup that is currently used on D7. I click on the Slideshow option and the following screen shows up. Then, I enter the name, and then I tried to browse the image. Somehow I can't seem to browse for the image (let alone attach it).

>

Is there a reason why? Is there something that I need to install?

# Answer
> 0 votes
I found out what was wrong. There was a missing JS file. Installed the missing JS file and now it is working.

---
Tags: 7, views
---


# Question
Title: How do I obtain the values from the checkboxes form element?
I have put some checkboxes in my custom form.

```
form.elements['zones'] = {
  title: 'Zones',
  type: 'checkboxes',

  options: {
    123: '123',
    456: '456',
    789: '789'
  }
};

```

In my form submission handler, I cannot get the submitted values.

```
function my_module_custom_form_submit(form, form_state) {
  try {
    drupalgap_alert('check values: ' + form_state.values['zones']);
  }
  catch (error) { console.log('my_module_custom_form_submit - ' + error); }
}

```

It just shows *\[object Object\]*. I tried to use a dump function to print it following http://www.openjs.com/scripts/others/dump\_function\_php\_print\_r.php, but it shows nothing. This dump function works when I print `form_state`. The text field and radio button have values, but all my checkboxes show *...*.

Even if I have set the default value in the form, it does not show anything when I print it out.

```
form.elements['zones'] = {
  title: 'Zones',
  type: 'checkboxes',
  options: {
    123: '123',
    456: '456',
    789: '789'
  },
  default_value: {
   456: '456'
  }
};

```

# Answer
> 0 votes
Do a `console.log(form_state.values.zones)` to see the data. Essentially it'll look something like this:

```
{
  123: '123',
  456: null,
  789: null
}

```

And this would indicate that only the `123` box is checked. I'm going by memory here, but it should be very obvious which values are checked and which ones are unchecked when looking at the `console.log()` values.

---
Tags: javascript
---


# Question
Title: Separate line items when line item details are different
As an ability the user might choose gift wrapping option for some of his/her products on add to cart form , what I did is creating a new product type called gift wrapping item, so site operators can add different kinds of wrapping options with different prices. I also altered the add to cart form so a new form item is added which gives the costumer the ability to choose a wrapping type, so far so good, user choice then is saved as a line item property (product ID of wrapping option is save in 'field\_wrapping\_option' which is added to product line item), and wrapping price is added to line item base price.

The problem is raised when user want to add 2 item from same product but he/she wants wrapping only for one of the two. In this case both products are stored in same line item and wrapping price also is added for them both.

I used `hook_commerce_cart_product_comparison_properties_alter` to force drupal create different line item when 'field\_wrapping\_option' are different on line items, but it didn't make things better, now every add to cart operation lead to new line item even when same wrapping option has chosen by user, and even worse situation happens when user first add a product without gift wrapping first and then adds a product with wrapping option which cause the first line item change into a product with gift wrapping.

Now the question is : `How to Separate line items when line item details are different?`

# Answer
> 1 votes
You could first have a look at Commerce Product Add-on module. That solution would split them per product type e.g. if you add one product with gift wrapping and one without you will have one line item for the product with quantity 2 and one for the gift wrapping with quantity 1. This gives the customer visibility of the exact pricing.

If however you still want to do it the way you described, the hook you mentioned should work.

```
function MY_MOULE_commerce_cart_product_comparison_properties_alter(
  &$comparison_properties,
  $line_item
) {
  $comparison_properties[] = 'field_wrapping_option';
}

```

Possible cause of trouble would be if the 'field\_wrapping\_option' of the line item being added is not set at all. The existing line item would always have the field set, even with an empty value, while you will have to set it for the incoming line item. It is possible that you set the field value only when gift wrapping is selected, try setting the field value to NULL if no gift wrapping is selected.

```
$line_item_wrapper->field_wrapping_option->set(NULL);

```

To further debug why line items are not properly combined, look at the 'commerce\_cart\_product\_add' function at the commerce\_cart.module file. The following code is the most relevant.

```
// Loop over each line item on the order.
foreach ($order_wrapper->commerce_line_items as $delta => $matching_line_item_wrapper) {
  // Examine each of the comparison properties on the line item.
  foreach ($comparison_properties as $property) {
    // If the property is not present on either line item, bypass it.
    if (!isset($matching_line_item_wrapper->value()->{$property}) && !isset($line_item_wrapper->value()->{$property})) {
      continue;
    }

    // If any property does not match the same property on the incoming line
    // item or exists on one line item but not the other...
    if ((!isset($matching_line_item_wrapper->value()->{$property}) && isset($line_item_wrapper->value()->{$property})) ||
      (isset($matching_line_item_wrapper->value()->{$property}) && !isset($line_item_wrapper->value()->{$property})) ||
      $matching_line_item_wrapper->{$property}->raw() != $line_item_wrapper->{$property}->raw()) {
      // Continue the loop with the next line item.
      continue 2;
    }
  }

  // If every comparison line item matched, combine into this line item.
  $matching_line_item = $matching_line_item_wrapper->value();
  break;
}

```

---
Tags: 7, commerce
---


# Question
Title: Allow role to edit node with same taxonomy term
I would like to allow a user to edit some node that have the same taxonomy term.

I created a taxonomy for enterprise and I referenced it in a field of user profile. I used this taxonomy in a content type too.

I wonder if it's possible to allow users to edit only nodes with the same taxonomy term, as in this example:

* Users :

+ Alex - enterprise : AAA
    + Paul - enterprise : PPP
* Nodes :

+ `1` \- enterprise : AAA
    + `2` \- enterprise : AAA
    + `3` \- enterprise : PPP

In this example:

* Alex can **edit** node `1` and `2` only, and see all.
* Paul can **edit** node `3` only, see all.

I tested taxonomy access control but I have to create a role for each enterprise to edit node with same term enterprise. But I have more than 100 enterprises.

# Answer
> 0 votes
A few year's back, I had to do this for a D7 site with 100s of content providers that could only post in specific areas. Did this by have a protected section taxonomy field on the user profile.

Then used hook\_node\_access to test if the node had a term that matched on of them on the user profile.

That's the basics.

I think I had to do a custom validator for the node create form to check that they were creating nodes with approved terms.

I also think the node create form and edit forms had the term lists cut down to just allowed terms by using a view as the source of the selection list.

Sorry for being general, I haven't worked on that site for years and don't have the code anymore.

# Answer
> 0 votes
there is a module exactly for that ATB module, only for D7, from module page:

> Provides very flexible, hierarchical node access control (content access control), for D7. Supports following flags: View Update Delete Grants are based on the relationship between the user-\>term\<-node. Taxonomy terms act as common denominators and allow many-to-many relationships between users and nodes. Organize your taxonomy terms hierarchically, this approach will allow for access grant inheritance. Nodes found in Views are also filtered out when user lacks permissions. Very simple, easy to understand logic and very little code. Uses lots of native functionality. Use any number of fields/vocabularies to control access for any number of content types. Has it's own automated tests. Detailed help section.

I have used this module for "group type" sites, combined with sub-user module, users and nodes that has exaclty the same taxonomy term can view/update/delete content at your will, this is done in node field settings; but it has a down side, there is a core locale module conflict, meaning that you can't traslate the site.

# Answer
> 0 votes
Instead of using the Taxonomy Access Control module (a D7 module with no D8 plans ...), you might want to give it a try to use the Group module, which allows for creating arbitrary collections of your content and users on your site, and grant access control permissions on those collections.

It is available as of D7, and has a D8 version also. It creates groups as entities, making them fully fieldable, extensible and exportable. Every group can have users, roles and permissions attached to it (refer to "What are the various roles supported by the Group module?" for more details about that).

For this specific question, you'd enable the `gnode` submodule, and for each group type you would define the appropriate permissions (view, edit, delete, etc) for the various Content Types. You'd probably want to create a Group type "Enterprise", and then create groups that you'd label similar to the taxonomy terms (AAA, PPP, ...) that you have defined.

For the Group permissions it seems that you would want to grant **edit** access to what, in Group, is called "Members". And combine that with **view** access (= *see all*) for:

* "Outsiders" (= logged in users who are not a member of a group).
* "Anonymous" (site visitors that are not logged it).

As per the "*I created a taxonomy for enterprise and I referenced it in a field of user profile*" in your question, you could use that user profile field to make a specific user a member of a specific group.

That's really "**it**", and it doesn't matter if your question is about D7, or D8 (either one will work).

For a sample configuration of the Group module, refer to my answer to "How to configure access for creating a custom LMS?".

# Resources

---
Tags: nodes, taxonomy-terms
---


# Question
Title: Custom authentication provider returns 403 for _access: 'TRUE'
The Jenny module implements an API and needs to authenticate based on this header...

```
Authorization: Jenny 8675309

```

Here is my API route...

```
jenny.api.get:
  path: '/api/jenny'
  defaults:
    _controller: '\Drupal\jenny\Controller\ApiController::get'
  methods: [GET]
  requirements:
    _access: 'TRUE'

```

The API returns data for any type of user, but for some roles additional data is included.

Here is my implementation for `AuthenticationProviderInterface`...

```
public function applies(Request $request) {
  if ($header = $request->headers->get('Authorization')) {
    if(strpos($header, 'Jenny ') !== FALSE) {
      \Drupal::logger('jenny')->info('this applies');
      return TRUE;
    }
  }
  return FALSE;
}

public function authenticate(Request $request) {
  \Drupal::logger('jenny')->info('authenticate');
  return $this->entityTypeManager->getStorage('user')->load(1);
}

```

This example code authenticates the admin user whenever there is an `Authorization: Jenny` header. Obviously the real code implements the logic to authenticate the proper user.

Here's what shows up in the log...

```
uid  type            message
0    jenny           this applies
0    jenny           this applies
0    jenny           authenticate
1    jenny           this applies
1    jenny           this applies
1    jenny           this applies
1    accesss denied  /api/jenny

```

It shows the uid changing, so it suggests that my authentication provider is doing it's part, but for some reason it's still coming back 403 access denied even though the route is `_access: 'TRUE'`. A request for `/api/jenny` without an `Authorization: Jenny` header returns the expected data.

This makes no sense to me. Could someone please point out what I'm doing wrong or why this isn't working? Thanks.

Upon further review, this is happening on all routes if there is an `Authorization: Jenny` header, even though the authentication provider is returning the admin user.

# Answer
Routes need to specify the authentication providers they want to support.

By default, that's session, so authenticating with something else is not allowed.

You do this by specifying `_auth: ['your_authentication_provider']` within the options: key of your route.
> 7 votes

---
Tags: 8, ajax
---


# Question
Title: How do I add attributes to a single menu's links?
I want to add some BEM classes to a single menu's links. I cannot find a way to do this in Drupal's GUI so I assume this must be done programmatically.

How would you go about this exactly? I've no idea what file any function would even go on...

# Answer
> 0 votes
You might try the Menu Attributes module. This looks like it will do what you want.

# Answer
> 0 votes
For drupal 8 try Menu Link Attributes or Link Attributes widget

---
Tags: 7, theming, navigation
---


title: Filter users by roles

text:
# Question
Title: Filter users by roles
I've a page showing the users. I wanted to categorized them, so I created roles and I'm grouping all the users according to their role. Now, I want to have a filter in the view to give the opportunity to the users to select the different types of users, example: employee, student, etc. The view will display the users according to the filter value.

How can I accomplish this?

# Answer
Have a look at the view ***People (User) view***, which is located at relative path `/admin/structure/views/view/user_admin_people`.

This view has a ***User role exposed filter***. You only need to implement the same filter in your view.

You need to select the same filter in screenshot below.
> 1 votes

# Answer
In FILTER CRITERIA click Add

Add **User: Roles** and expose the filter.
> 1 votes

---
Tags: views, users
---


title: Transactional entities?

text:
# Question
Title: Transactional entities?
I'm working on a custom Drupal 8 module. In a form submit function, I need to create several entities of different types. I am worried about what will happen if something goes wrong in the middle of the operation, as it will be difficult to clean up the mess.

So my question is: is there any kind of transactional mechanism for entities, similar to SQL transactions, so that I could conveniently rollback in case of an error?

If not, what strategy would you suggest?

# Answer
You can wrap all the entity save calls in a further transaction with Connection::startTransaction for a given database connection. Inject the `database` service into the form using FormBase::create

Catch using DatabaseExceptionWrapper and rollback :-). This is similar to Drupal 7 behavior as well.

It would be best to provide a unique name for the transaction as the transaction stack is fairly basic.
> 2 votes

# Answer
it is a solution:

```
$database = \Drupal::database();
$transaction = $database->startTransaction();
$id_branch = null;
try {
  if(empty($id_branch)) {
      throw new \Exception('Empty: Branch Entity id.');
  }
  $Branch = Entities::load($id_branch);
  $branch_address = $Branch->getAddress();

  for ($i = 0; $i < 8000; $i++) {
    $values = array(
      'entity' => $id_branch,
      'name' => 'Store ' . $i,
      'address' => $branch_address,
    );
    $Store = Store::create($values);
    $Store->save();
  }

}
catch (\Exception $e) {
  $transaction->rollback();
  watchdog_exception($e->getMessage(), $e);
  throw new \Exception(  $e->getMessage(), $e->getCode(), $e->getPrevious());
}

```
> 0 votes

---
Tags: entities, database, 8
---


title: Get ID in HOOK_preprocess_container

text:
# Question
Title: Get ID in HOOK_preprocess_container
I'm currently working a styling of a drupal 8 website. And I'm trying two things.

In HOOK\_preprocess\_container I want to output a block, I got the block script figured out but I want to filter and output only when the Container ID matches a certain ID. Can someone help me out with this?

Thanks in advance.

My current HOOK:

```
function HOOK_preprocess_container(&$variables) {
  //something like this
  $containerID = //get container ID;

  $block = \Drupal\block\Entity\Block::load('block_id');
  $block_content = \Drupal::entityTypeManager()
    ->getViewBuilder('block')
    ->view($block);

  if($containerID == "containerID"){
    $variables['containerblock'] = $block_content;
  }
}

```

# Answer
> 0 votes
You should be able to get that with:

```
$container_id = $variables['element']['#id'];

```

---
Tags: 8, forms
---


# Question
Title: Using path aliases how to identify node IDs from database and based on these IDs how to publish them?
I have a content type called article. For this content type, I unchecked the "*Published*" checkbox under the publishing options tab.

I have 30000 nodes I changed to unpublished. Among those, I want to publish 900 records. I have the node URLs.

Using the path aliases, how to get the node IDs? Once I have the node IDs, how can I publish those nodes?

# Answer
You can use `drupal_get_normal_path()` to get the `node/id`-paths for each of them.

Then you can use the following code to publish them.

```
// Load the node object.
$node = node_load($nid);
// Set the status property to 1.
$node->status = 1;
// Re-save the node.
node_save($node);

```
> 2 votes

# Answer
If you have the path alias, you can easily get the normal path and then the node object with two single functions. I assume you have the path alias available in the `$path_alias` variable.

```
$path = drupal_get_normal_path($path_alias);
$node = menu_get_object('node', 1, $path);

```

Once you have the node object, you just set `$node->status` to `NODE_PUBLISHED`, and save the node. So the full code becomes the following.

```
$path = drupal_get_normal_path($path_alias);
if ($node = menu_get_object('node', 1, $path)) {
  $node->status = NODE_PUBLISHED;
  node_save($node);
}

```

I am not sure how much safe it's assuming the path aliases are for nodes, but just to be sure, and avoid trying to load a node when Drupal didn't find any normal path matching the path alias, I would use the following code.

```
$path = drupal_get_normal_path($path_alias);
if (strpos($path, 'node/') === 0 && ($node = menu_get_object('node', 1, $path))) {
  $node->status = NODE_PUBLISHED;
  node_save($node);
}

```

Notice that `===` is necessary, since `strpos()` can either return `0` to mean the path starts with `'node/'`, or FALSE to mean `'node/'` was not found in the path. (In PHP `0 == FALSE` is `TRUE`.)
> 1 votes

---
Tags: 7, nodes
---


title: Embed a "node add" form in a page

text:
# Question
Title: Embed a "node add" form in a page
I'm looking for a way to embed a "node add" form on a landing page. I was using Form Block, but it appears to bring many error because I was using a development snapshot version.

# Answer
You can use:

```
module_load_include('inc', 'node', 'node.pages');
$form = node_add('nodetype');
print drupal_render($form);

```
> 29 votes

# Answer
Although Daniel Wehner's answer is absolutely correct and works, I wanted to add two common problems I faced with this approach and workarounds how I overcome those problems. First my code, then the explanations:

```
global $user;

module_load_include('inc', 'node', 'node.pages');

$node = (object) [
  'uid' => $user->uid,
  'name' => (isset($user->name) ? $user->name : ''),
  'type' => 'YOUR_NODE_TYPE',
  'language' => LANGUAGE_NONE,
];
$form = drupal_get_form('YOUR_NODE_TYPE' . '_node_form', $node);

print drupal_render($form)

```

Why I did it this way, instead of Daniel's simple `node_add`?

Problem 1: `node_add()` function changes the page title to **Create 'node type'**, this is hard coded in the function.

Workaround 1: Instead of using `node_add` function, I've copied the code and removed the `drupal_set_title`. The above code is the same code as the `node_add` function, except from this one line.

Problem 2: In the embedded form some ajax functions didn't work. For example if you have a field that can have unlimited values, so that you have an 'Add another item' button, or if you have an upload file field in your form, they don't work.

Workaround 2: In your custom module, implement `hook_menu_alter()` for ajax call paths, and include `node.pages.inc`.

```
function YOURMODULE_menu_alter(&$items) {
  $items['file/ajax']['file path'] = drupal_get_path('module', 'node');
  $items['file/ajax']['file'] = 'node.pages.inc';
  $items['system/ajax']['file path'] = drupal_get_path('module', 'node');
  $items['system/ajax']['file'] = 'node.pages.inc';
}

```
> 18 votes

# Answer
If I use the accepted answer's code...

```
module_load_include('inc', 'node', 'node.pages');
$form = node_add('nodetype');
print drupal_render($form);

```

...inside of a page callback function, then `print drupal_render..` this results in a completely un-themed (broken-looking) page.

So instead, I just `return`'ed the `$form`:

```
module_load_include('inc', 'node', 'node.pages');
$form = node_add('program_registration');
return $form;

```
> 0 votes

---
Tags: 7, forms, nodes
---


# Question
Title: How to grant permissions for some role to execute custom Rules Components?
I created a view (table) and i asociated views bulk operations. I created 4 rules components. I have permissions only for `user/1` (admin). Another user role (eg. editor) can't see these options. "editor" user can see only "DELETE ITEM" rule components.

In permissions I have only the default actions (components); I created 4 new Rules Components, and these aren't displayed in `Admin > People > Permissions`.

Is there another method (trick) to give permissions for another role for custom Rules Components? Am I missing something?

# Answer
> 1 votes
When you **edit** the configuration of a custom Rules Component, within its `Settings`, there is an option with label ***Configure access for using this component with a permission*** (disabed by default). And with some additional explanation below it like so:

> By default, the action for using this component may be only used by users that have access to configure the component. If checked, access is determined by a permission instead.

If you enable this option (= add a checkmark), it'll display a table that looks similar to this one (whereas in this sample I only had a single custom role defined, i.e. "editor", and the label of my Rules Component is "ABC"):

```
!PERMISSION              !ANONYMOUS USER!AUTHENTICATED USER!ADMINISTRATOR!EDITOR!
!--------------------------------------------------------------------------------
!Use Rules component ABC !      O       !         O        !       O     !   O  !
!--------------------------------------------------------------------------------

```

If you'd check (e.g) the checkbox below "Editor", then a user with role Editor would be allowed to execute the Rules Component ABC. And such user will also see it in the list of possible (allowed!) bulk operations in a VBO view (users without the required role will not be able to select it in such VBO view).

PS: user `user/1` is always considered as an exception to anything about permissions (so never consider that user as a reliable testcase for anything about permissions).

# Answer
> 0 votes
If you've enabled "Action permissions" check the role has permission to "Execute \[action\]" in `Admin > People > Permissions`

---
Tags: 7, rules, users, views
---


# Question
Title: Change the rendered output of a Message entity
I'm using the Message module to create messages on certain events, for example, on forum node creation:

"X has posted a new thread in the Y forum."

I've got a view that spits all of these out.

I now want to create a new view that shows the same messages, but in this view, I want to change the output of the above message to:

"You have posted a new thread in the Y forum."

Every time the node's author matches the currently authed user.

---

Now my thoughts would be that I could somehow intercept the output of either the token (X) or override the whole message entity template, but I'm not entirely sure how to go about this.

Another thing I tried was to create a new user token, called "Username or you", which would output "you" if the associated message node matched the authed user, or the username if not. However, I'm not sure how I could get the message object. It's worth noting that I have the token:

```
[message:field-forum-post:author:username_or_you]

```

So if I could follow the trail back to "message" and get the message id, I'd be all set.

Any pointers?

# Answer
> 1 votes
See the Messaging documentation, specifically this overview on new features. You likely want to override the tokens provided using a `callback` which is supported by the module:

> Callbacks: sometimes we can’t use the token system, for example if we need to show different results based on the value of \_two different fields. This is an advanced feature, which is meant for developers, and is documented in the module.

I've not done this myself yet, but I've used the Message module and Views -- digging through the module and documentation should get you there now that you know it's possible.

From the message\_example README it sounds like you want an activity stream:

> The UAS (User activity stream) view is dependent on Panels, as it uses "Panel fields" as a row plugin, along with the Message's partials.

Which you should be able to look at for inspiration in the example module.

# Answer
> 0 votes
If you are willing to (also) use the Rules module, you might be able to make a token such as `username_or_you` (as in your question ...) available by using the Replacement patterns for each message type.

So the answer to your question is "***Whatever token you're missing, just make it available via Rules, by creating a replacement token for them***". Refer to the answer to What's the purpose of "Replacement tokens" of a Message type? for way more details on that.

These *Replacement tokens* are really a hidden gem about how Rules integrates with Message. For an example to see them at work, refer to my answer to "Which user related token(s) can be used to create a Rule for setting up a message type?".

---
Tags: 7, message-subscribe
---


# Question
Title: All images within my articles have a link of their own: why?
The article content type has a field to upload images with the article text (body and teaser). I noticed that every image I upload gets its own URL after submitting the article, e.g. http://www.example.com/imagejpg.
This is messing up my Google SEO as each image has its own URL, and it is showing up in the search index for my domain.

Is there any way to stop these images from having their own URL?

# Answer
All entities in drupal have their own page, you can use the Rabbit hole module to control what should happen when an entity is being viewed at its own page.

Inside module there is a sub-modules for each entity type, you have to install rabbit\_hole and rh\_file.
> 0 votes

---
Tags: media
---


# Question
Title: How to modify ds_bootstrap_layouts templates to add more layouts?
I'm using the Display Suite Bootstrap Layouts module in Drupal 7, and I want to create additional layouts.

For example, I want the 4-4-4 stacked turned into a double 4-4-4 stacked. I know how to access the files and modify them, but it causes errors and it doesn't show up in the backend.

>

How do I add more layouts?

# Answer
> 0 votes
1. Implement the following hook

```
function MODULENAME_ctools_plugin_directory($module, $plugin) {
  return 'plugins/' . $plugin;
}

```

You can change the name of the 'plugins' directory, but cannot change the following.

2. Next you create a folder inside the 'plugins' directory and call it 'layouts' \<--don't change. Then place your custom layouts in that directory.
3. Your .inc file will look something like this

```
$plugin = array(
    'title' => t('LAYOUT TITLE'),
    'icon' => 'ICON.png',
    'css' => 'CSS_FILE.css',
    'theme' => 'NAME OF TEMPLATE FILE W/O .tpl.php'
    'panels' => array(
      'top' => t('Top'),
      'top_left' => t('Top Left Column'),
      'top_right' => t('Top Right Column'),
      'middle' => t('Middle'),
      'bottom' => t('Bottom')
  ),
);

```
5. Panels will automatically scan your layouts folder for new layouts. **DONT FORGET TO CLEAR THE CACHE**. Your new layout will appear in the 'Miscellaneous' section when selecting a layout for your panel.

---
Tags: bootstrap-theme
---


# Question
Title: How can I get additional fields from Search API query?
I have Search API DB backend where I will be retrieving thousands of results and I need some fields to get out of there as well, beside search item id, since doing additional query to MySQL with IN condition consisting of thousands of entries is nonsense.

Can't find any methods to do this in the code so far though.

I think the query option `search_api_retrieved_properties` is the key, but I was not able to make it work yet.

---

I have added the fields via `hook_search_api_db_query_alter` on tagged query but they are not present. Calling getField() on the result item always queries the source entity(= entity\_load operation).

# Answer
Unfortunately, it looks like this is impossible.

Looking at `\Drupal\search_api_db\Plugin\search_api\backend\Database::search`:

```
  $result = $db_query->execute();

  foreach ($result as $row) {
    $item = $this->getFieldsHelper()->createItem($index, $row->item_id);
    $item->setScore($row->score / self::SCORE_MULTIPLIER);
    $results->addResultItem($item);
  }

```

The `$item` will receive only the item\_id from the fetched row, so all added fields are lost :(
> 0 votes

---
Tags: 8, search
---


title: Multistep Registration Form

text:
# Question
Title: Multistep Registration Form
while googling and reading documentation and API, I've seen multiple solutions for "combining" 2 forms into one, and thus creating a multistep form.

What I want though, not even sure if it's doable, is to "split" my (huge) user registration form into 2 steps, where the value of one field (the only one in step 1) would determine which fields should show up in step 2.

I wouldn't like to drop the entire registration form and re-create it in code or in another way and somehow re-implement the whole user registration process. Is that possible?

EDIT: to avoid misunderstandings, what I need to do is an "actual" multistep form, with submitions between steps, and not some front-end handling. That is, I want the whole thing to be javascript independant.

EDIT2: to clarify even further, the task is figure out how/if possible to pretty much split any "edit" form to 2 parts. The current question does ask about the user/edit and/or user/register form specifically, but in order to come up with a more generalized solution, one might also want to split a node/edit form in to 2 parts. That's what I am really asking about. Splitting an entity/edit form in to 2 (or more) steps.

# Answer
One way to do this would be to use the Conditional Fields module (disclaimer: noted as not ready for production for D7). The way to do it with your own code would be to use the States API (the Conditional Fields module is just a GUI to States API, basically).

Using Conditional Fields, you can set it so that, for example, based on the value selected for Field A, a number of fields would be shown or not shown as per your requirements.

**EDIT**: To split the form into two steps, you can use the Field Group module, which provides a "multipage steps" feature. To configure this, you will need to create a fieldgroup of type *multipage* for each page you want to have on the user registration form, and then place the appropriate fields under each page (on the user account manage fields screen).

Note: The Conditional Fields and Field Group module will display everything as one giant page if Javascript is disabled. I don't know any way around this.
> 2 votes

# Answer
Take a look at the Profile2 module. When I first encountered it, I was a little confused about its purpose and why 18k+ sites found it so useful :-p Turns out it is great for storing and organizing user information when you have many fields associated with each user.

The Profile2 module creates and maintains new profile entities attached to user accounts. For the uninitiated, in Drupal 7 an entity is a set of information, usually with fields attached. Nodes are entities, users are entities, relations are entities, etc. Profile entities behave similar to new nodes, except that they are attached to user accounts. Users are able to edit their profiles on a separate page from the actual account page, or as part of the account page itself (depending on the settings you choose).

For your project, here's what I'd recommend:

1. Install and enable Profile2. This automatically creates a new default "Main" profile.
2. Edit the settings for the "Main" profile at `admin/structure/profiles/manage/main`. Uncheck "Show during user account registration" and check "Provide a separate page for editing profiles".
3. Add the additional user fields you want at `admin/structure/profiles/manage/main/fields`. If there are still more fields than should be stored and edited on a single page, create an additional profile type at `admin/structure/profiles/add`, or use Field group (Javascript based) to break the form down into groups.
4. Install and enable Rules. Create a Rule that directs new user accounts to the profile edit page: `profile-main/[account:uid]/edit`. If you needed additional profiles to break down the form further, add additional Rules directing the user to those pages by reacting to the event "After saving a new profile".

Rule export code:

```
{ "rules_direct_new_accounts_to_profile_edit_page" : {
    "LABEL" : "Direct new accounts to profile edit page",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules" ],
    "ON" : [ "user_insert" ],
    "DO" : [ { "redirect" : { "url" : "profile-main\/[account:uid]\/edit" } } ]
  }
}

```

This has the benefit of being able to separate the account settings (e-mail, username, password) from the information about the user (the profile fields). Using this configuration, you can achieve the desired multi-step user registration form without writing a line of code. The only caveat that you should be aware of is that a user can leave the workflow after creating an account without creating a profile (even though Rules automatically directs them to the profile edit page, there's nothing keeping them from clicking a link to another part of the site). Additional Rules may be necessary to require the user to complete the profile before using the rest of the site.
> 1 votes

# Answer
Have you looked into the Chaos Tools form wizard implementation found here. I have done something similar for a registration form following those instructions and integrating some profile2 fields in the multistep form as well. Had to create a custom module that had the page callbacks and also handled the form fields. I can get into more detail about how I handled it if this is a path you're wanting to follow.
> 1 votes

# Answer
Here's a totally different approach to adding an "actual" multi-step form that may or may not work for you. I did something similar to the following on a site I built.

On this site, users had four possible roles. They could have any combination of the roles: all 4, none, or role A and B but not C and D, etc. Each role has its own set of associated profile fields that should only be shown to users of that role.

On the user registration form, I allowed users to select their roles with checkboxes. Then, using the Rules module, I awarded the roles upon account registration to each user. I also used Rules to automatically created a set of nodes for each user upon account registration. These nodes are special content types that contain the profile questions for each role. They are linked to the user account via the Relation module.

Then, I built a set of views and laid out the user profile with the Panels module so that it shows the fields from the different nodes for the roles on the user profile page. This was a very complex set up, but it allows me to give users separate edit links to the different parts of their profile, ensures that only users with the appropriate role will be asked to fill in certain parts of the profile, and works without Javascript.
> 0 votes

# Answer
I'm just starting in Drupal and working on something similar but I have not really pursued it - I used the Workflow module what it does is I am able to add a (workflow) field to the registration form to link to another view. There maybe some issues on the data but I was thinking that all I had to do was play around with the registration state (promote it). As mentioned I am just a beginner and I have not really seen this working in totality. but I think you should look into this as a possible solution.
> 0 votes

# Answer
a. for multistep node form, use msnf. it works great! b. for creating multistep (server side) user registration i haven't found any module to fit my needs so i had to do it myself. here's what i did:

my setup: email\_registration + ife + asaf

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function custom_form_user_register_form_alter(&$form, &$form_state, $form_id) {
    // initialize step
  if (empty($form_state['step'])) {
    $form_state['step'] = 1;
  }

    // adjust form for step 1
  if ($form_state['step'] == 1) {
        // hide default submit button
    $form['actions']['submit']['#access'] = FALSE;
        // add custom button
    $form['actions']['next'] = [
      '#value' => 'Next step',
      '#type' => 'submit',
      '#validate' => [
                // step 1 validation callback
        '_custom_user_register_form_step1_validate',
                // only if you use ife
        'ife_form_validator'
      ],
            // step 1 submit callback
      '#submit' => ['_custom_user_register_form_step1_submit'],
            // limit validation only for fields below
      '#limit_validation_errors' => [
                // add all fields that should be validated in step 1
        ['field_phone'],
        ['mail'],
      ],
    ];

        // hide all fields that belong to step 2
    $form['field_age']['#access'] = FALSE;
  } else if ($form_state['step'] == 2) {
        // hide fields that belong to step 1
    $form['field_phone']['#access'] = FALSE;
    $form['account']['#access'] = FALSE;
        // limit validation only for fields below
    $form['actions']['submit']['#limit_validation_errors'] = array(
            // add all fields in step 2
      array('field_age'),
    );

        // add custom validation callback for step 2
    $form['#validate'][] = '_custom_user_register_form_step2_validate';
        // only if you use ife
    $form['actions']['submit']['#validate'][] = 'ife_form_validator';

        // add custom submit
    array_unshift($form['#submit'], '_custom_user_register_form_step2_submit');
  }
}

```

and the callbacks:

```
function _custom_user_register_form_step1_validate(&$form, &$form_state) {
  // validate here
}

function _custom_user_register_form_step1_submit(&$form, &$form_state) {
  // increase step
  $form_state['step'] = 2;
  // store step 1 values for later use
  $form_state['storage'] = $form_state['values'];
  // rebuild form
  $form_state['rebuild'] = TRUE;
}

function _custom_user_register_form_step2_validate(&$form, &$form_state) {
  // validate here
}

function _custom_user_register_form_step2_submit(&$form, &$form_state) {
  // add values from $form_state['storage'] to $form_state['values']
}

```
> 0 votes

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


title: How do I print custom user fields?

text:
# Question
Title: How do I print custom user fields?
I am trying to customize the authored by information for all of my nodes that prints the User First and Last Name, which are custom fields on the User Profile.

1. I copied the node.html.twig template into my theme
2. I added the following code to load the user information in my preprocess function

```
function blend_preprocess_node(&$variables) {

// Load the current user.
$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());

// get field data from that user
$firstname = $user->get('field_first_name')->value;
$lastname = $user->get('field_last_name')->value;

// some default getters include
$email = $user->get('mail')->value;
$name = $user->get('name')->value;
$uid= $user->get('uid')->value;

}

```
3. I added this code to node.html.twig

```
{{ title_prefix }}   {% if not page %}
<h2{{ title_attributes }}>
  <a href="{{ url }}" rel="bookmark">{{ label }}</a>
</h2>   {% endif %}   {{ title_suffix }}

{% if display_submitted %}

<div class="posted">

    <div class="services-icon">
      {{ content.field_services }}
    </div>

  {{ author_picture }}

  <div{{ author_attributes }}>
    {% trans %}Submitted by {{ firstname }} {{ lastname }} on {{ date|date("m/d/Y") }}{% endtrans %}
    {{ metadata }}
  </div>
</div>   {% endif %}
{# We hide the comments and links now so that we can render them later. #}   <div{{ content_attributes }}>
{{ content|without('comment', 'links', 'field_tags', 'field_services') }}   </div>

{% if content.field_tags|length and not is_front %}
{{ content.field_tags }}   {% endif %}
{{ content.links }}   {{ content.comment }} </article>

```

How do I make variables (mostly fields) from different entities available to print in different template files?

# Answer
Assuming this information is from the user profile.

You could do the following

**blend.theme**

```
function blend_preprocess_node(&$variables){
    $node = $variables['node'];
    $variables['firstname'] = $node->getOwner()->field_first_name->value;
    $variables['lastname'] = $node->getOwner()->field_last_name->value;
}

```

From there you can use `{{ firstname }}` and `{{lastname}}` anywhere in your template.
> 9 votes

# Answer
The accepted answer didn't work for me on Drupal version 8.3.4 and more. Actually the `$node = $variables['node']` didn't work so I found out the following method to make it work.

On the .theme file (in this example blend.theme), I used the following code.

```
function blend_preprocess_node(&$variables){
  $node = \Drupal::routeMatch()->getParameter('node');
  $variables['firstname'] = $node->getOwner()->field_first_name->value;
  $variables['lastname'] = $node->getOwner()->field_last_name->value;
}

```
> 0 votes

---
Tags: theming, 8
---


# Question
Title: How to test any features that require authentication?
I am just getting started with BeHat and I'm able to successfully run tests that do not require authentication. But, anything that requires authentication is failing.

STATEMENT (or any logged in statement)

Fails with ERROR MESSAGE .

But, if I add 'not-logged-in' as a possible class for logged in, then the test passes. This tells me that I am not successfully logging in with my tests. The test is actually finding a class 'not-logged-in' when it is testing to see if it's logged in.

I am getting email notification that a user has been created when the test runs. So, I know that a user is being created, but not successfully logging in.

```
Feature: Authentication
  In order to make sure Behaviour testing is working
  As a behat test user
  I want to make sure I can log in

  Scenario: Anonymous access
    Given I am on the homepage
    Then I should see "Login"

@api
  Scenario: Test Being Logged In
    Given I am logged in as a user with the "administrator" role
    Then I should see the link "Test Link"

```

My behat.yml file looks like this:

```
default:
  suites:
    default:
      contexts:
        - FeatureContext
        - Drupal\DrupalExtension\Context\DrupalContext
        - Drupal\DrupalExtension\Context\MinkContext
  extensions:
    Behat\MinkExtension:
      goutte: ~
      selenium2: ~
      base_url: http://mysite.localhost
    Drupal\DrupalExtension:
      blackbox: ~
      api_driver: 'drupal'
      drush:
        alias: 'local'
      drupal:
        drupal_root: '/Users/myfolder/sites/mysite'
      region_map:
        footer: "#footer"

```

# Answer
> 0 votes
As mentioned in my question, it was pretty clear that Behat was failing to login, so I began to look for modules that might interfere with the login process.

It turns out that we are using the module AntiBot (https://www.drupal.org/project/antibot) and when we disabled this module, we were able to run tests that involved successfully logging into Drupal.

---
Tags: testing
---


# Question
Title: Why are my absolute links becoming relative paths in webform email template?
I have a webform where end-users can upload images files. My office users were reporting that when they received and email notice of a submission, the links to the images are broken.

I was working on updating the email template for webform submissions. I created `webform-mail-34981.tpl.php`, which is the nid of the webform in question.

First I broke the fields out into separate tokens, but I still got broken links.

Tokens in expressions such as this

```
[submission:values:photo_5]
[submission:values:photo_5:nolabel]

```

gave relative links, with out the domain name, like this

```
<a href='/sites/default/files/webform/index4_17.jpg'>www.example.com/sites/default/files/webform/index4_17.jpg</a>

```

As you can see, when the user would click on that link, the browser says it can't find the server, because it has a relative path.

Thinking it was a problem with the token, I added code to construct the anchor tag from the `fid`:

```
foreach ( $fids as $fid ) {
  $file = file_load($fid);
  $url = file_create_url($file->uri);
  echo "Plain URL: $url<br>\r\n";
  echo "Anchor tag: <a href='$url'>$url</a><br>\r\n";
}

```

To my suprise, I still got links with the correct URL value in the anchor tag, but a relative path in the `href`!

In doing some debugging, I added a `die()` statement to the template, so that I would see the template before it had its tokens replaced. I was further surprised when I saw that the template output had FQDNs in the href propreties:

```
Photo 4
[submission:values:photo_4]
[submission:values:photo_4:nolabel]

Photo 5
[submission:values:photo_5]
[submission:values:photo_5:nolabel]

Plain URL: http://example.com/sites/default/files/webform/index2_36.jpg<br>
Anchor tag: <a href='http://example.com/sites/default/files/webform/index2_36.jpg'>http://example.com/sites/default/files/webform/index2_36.jpg</a><br>

```

So, in webform-mail-34981.tpl.php, the URI values in the href of the tags are FQDNs, which is what we want. Some time after, they are being replaced with relative paths, which are broken for end-users.

When/where is this happening? I did not create the site, I'm just a contractor working on it, so I'm not aware offhand if there is custom code that might be doing this.

We do have `webform-mail.php`, but it appears to be a stock template. It doesn't seem to have any code that would make paths relative:

```
<?php print ($email['html'] ? '<p>' : '') . t('Submitted on: [submission:date:long]'). ($email['html'] ? '</p>' : ''); ?>

<?php if ($user->uid): ?>
<?php print ($email['html'] ? '<p>' : '') . t('Submitted by user: [submission:user]') . ($email['html'] ? '</p>' : ''); ?>
<?php else: ?>
<?php print ($email['html'] ? '<p>' : '') . t('Submitted by anonymous user: [submission:ip-address]') . ($email['html'] ? '</p>' : ''); ?>
<?php endif; ?>

<?php print ($email['html'] ? '<p>' : '') . t('Submitted values are') . ':' . ($email['html'] ? '</p>' : ''); ?>

[submission:values]

```

How can I find out where this is happening?

**Edit** I've installed the `mail_logger` module to try to get a more objective look at what is going on. It looks like something in the templating system is re-writing absolute links into relative links.

```
Mail Type:
webform_submission
Date Sent:
August 20, 2017 - 5:09pm
User IP Address:
127.0.0.1
Mail Class:
HTMLMailSystem
...

Photo 1<br /><a href="/sites/default/files/webform/my_export.png">my_export.png</a><br /><a href="/sites/default/files/webform/my_export.png">my_export.png</a></p>
<p>Plain URL: <a href="/sites/default/files/webform/my_export.png">http://mysite.dev.dd:8083/sites/default/files/webform/my_export.png</a><br /><br />
Anchor tag: <a href="/sites/default/files/webform/my_export.png">http://mysite.dev.dd:8083/sites/default/files/webform/my_export.png</a><br /></p></div>

```

**Edit 2**

I've been doing some more troubleshooting. Found two more pieces of information:

1. HTMLMimeMail mail system is causing the links to change. When I removed HTMLMimeMail from the webmail key, then plan text emails had the full link.
2. Pathologic is not re-writing the link either way. I looked at pathologic settings on our site, and it was initially set to relative URLs. I thought this might be the cause of the problem, but I changed it to absolute paths. I still got links with relative paths. To make a stronger test, I specified the domain name to `example.com` in pathologic settings. I still got relative links in the email (I cleared the cache after changing pathologic settings). So, I believe pathologic can be ruled out.

**Edit 3** I debugged the final output of the `HTMLMailSystem::format()` method, and at the end of the function, the output has the domain name in the links. I'm presently at a loss for the next thing to look at, would appreciate any help.

# Answer
I don't know if this answer causes this question to be disqualified on this site, but it turns out that the pathologic module is causing relative links.

I disabled the pathologic module on a dev environment, and now the links are no longer relative.

I'm working on troubleshooting the settings to keep my links from becoming relative.
> 1 votes

# Answer
Try to change the weight of your custom module in order run after pathlogic module, So you can keep pathlogic module enabled without affecting your code.
> 0 votes

---
Tags: theming, webforms, tokens
---