# Question
Title: Why does the selected payment method comparison always fail?
I'm trying with following simplified rule but nothing happens if using `maro_credits` as payment method!?

```
{ "rules_pay_with_maro_credits" : {
"LABEL" : "pay with maro credits",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules_conditional", "rules", "commerce_payment", "commerce_pos" ],
"ON" : { "commerce_pos_transaction_completed" : [] },
"DO" : [
{ "CONDITIONAL" : [
{
"IF" : { "commerce_payment_selected_payment_method" : { "commerce_order" : [ "order" ], "method_id" : "maro_credits" } },
"DO" : [ { "drupal_message" : { "message" : "aklfjaipwoejfipasjfijasdfas" } } ]
}
]
},
{ "LOOP" : {
"USING" : { "list" : [ "order:commerce-line-items" ] },
"ITEM" : { "list_item" : "Current list item" },
"DO" : []
}
},
{ "drupal_message" : { "message" : "test pos event" } }
]
}
}

```

However the orders in admin - store - orders show up with the payment method, as shown in this screenprint:

https://i.stack.imgur.com/Lbiow.jpg

Anyhelp?

Edit: I used the mentioned selected\_payment\_method comparison method that pierre referenced below from start on.

cant add more than 2 links, so i have to add multiple pictures like this i guess: first you see the selected\_payment\_method input for the version in the actions with conditional and the rule in the view also with what happens

i after changed the rule to use the conditions directly to show that also there it does not work

https://i.stack.imgur.com/UsxWa.jpg

is this more clear now? or you need more specification?

edit2: in the end i added some screens showing the fields that could be found (nothing with payment method)

Edit3: Ok I added some descriptions in the pictures on imgur to clarify a bit. In the end I want to be able to subtract user points form users that pay with "maro credits" (that part already works)

As you see in the screenshots I changed the rule having only the event pos transaction completed (that works!)

then condition selected payment method as shown

and action post a message

as you see in following screenshot that does not work (in the orders list you see there is the order with the payment method maro credits

I hope its clear now?

Ah forgot: in the last screenshots you see all the fields I would be able to chose from and there is none with payment method (and i think that is the problem...?)

# Answer
> 1 votes
The condition you are using checks `$order->data['payment_method']`, which is the payment method selected by the user during checkout. An order can actually have multiple payment methods, 1 per transaction, although on a standard setup usually only 1 can be selected initially. Since POS doesn't run through a checkout and allows the customer to pay with multiple methods, such as cash and then the remainder on card, it does not have a "selected" payment method.

I don't see any easy way to get the specific transaction info in rules, so it seems like you have 2 options.

* Hacky - Add code to the completeTransaction action that the orders selected payment to the most recent transactions type
* Better - Create a custom condition that will check if any of the transactions in an order contain the specific payment\_method

# Answer
> 1 votes
### Part 1 - Getting your rule to work

Try to add a Rules Condition `Entity has field` to make the appropriate field available for further processing in your Rules. That's also what is mentioned in the Rules UI when you're adding a "data comparison" condition: somewhere it says:

> The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type').

Don't believe me (yet) about my recommendation here ... first add an extra Rules Action as your very first Rules Action, to simply display the actual value of that field you try to use within the "If" of your Conditional Rules construct ... Without such "entity has field" Rules Condition, I bet the value of that field will be shown as empty (or blank). Which would then also explain why your "If" always results in a FALSE ...

For a video tutorial that illustrates the importance of this `Entity has field` condition, refer to Data types and data selection, especially what is shown between about 13:30 and 17:30 in that video.

**Note**: it's hard to tell from the current content of your question what the exact field (for which to add such Rules Condition) should be in your case. But my best guess is some field about the payment method (possibly `method_id`?)

### Part 2 - Simplify your rule

From the current content of your rule, it seems that you want to perform a Rules Loop as a Rules Action, but only if some condition (the "If" you added using "Conditional Rules" module) is true. And then as the very last Rules Action the rule shows that `test pos event` message.

If this very last message is just for debugging (i.e if it is not really needed after you get it to work anymore), then it seems to me that you could replace that "If" (added using Conditional Rules) by a regular Rules Condition. And by doing so your rule would not require the Conditional Rules module anymore.

### Plan B

As per the comment posted below this answer, you may want to try a completely different approach ... which is based on this commit, and related to issue # 1278156:

* Use the Rules Condition `Selected payment method comparison`, located within the Commerce Payment group.
* Check if its value is equal to your 'maro\_credits'.

---
Tags: 7, commerce, rules
---


# Question
Title: How to add a Login / Logout link in Main navigation menu?
How can I add a Login link to the "Main navigation" menu?

When a user clicks on the link, it should take them to the /user/login page. Once they login, the link should change to say "Logout" instead of "Login".

Is there any way to add such a link?

# Answer
We don't need to depend on Bootstrap theme or our programming skills to move system "*Log out*" link on any other menu. Drupal allows us to make it easily.

Additionally we can just create two custom "*Log in me here please*" and "*Get me out of there*" links with **/user/login** and **/user/logout** paths relatively. This is better because unlike the system "Log out" link it gives us to create as many log in/out links as we want with custom attributes. As the user logged in they'll see only "*Log out*" link and vice versa. The only caveat is that you will see probably both links together because you are logged in at the time of testing the links. And this is normal as you have "*Link to any page*" permission as administrator. Disable this permission and try again.
> 13 votes

# Answer
> Long story short, you create 2 different Menu versions, one with login, another with logout, and give each version different visibility roles.

1) **Edit menu**, and add the Logout Link.

2) Now all you gotta do is **configure** your main menu link block

**Then in Roles, check mark ☑ Authenticated users and also ☑ Administrator**

3) **Now create another Menu (`/admin/structure/menu`) which has the "login" link and all other other menu links you need.**

4) Then go to blocks (`/admin/structure/block`) in **Primary Menu** (Assuming you're using Bartik, may have a different name if you're using a custom theme) click add, and add the Menu you just created and configure it. This time for Roles, only check mark ☑ Anonymous
> 4 votes

# Answer
There is a better way of doing this. What you want to do is create your own plugin and extend the MenuLinkDefault class. The best place to look is the Drupal/User module which provides the LoginLogoutMenuLink implementation.

You can either define your own plugin if you want to for instance change the text or logic. Alternatively, you can simply point it at the existing plugin to save yourself time and simply put the existing implmee. Here is some sample code:

**Simple version:**

* Create `my_module/my_module.links.menu.yml`

```
my_module.logout:
  weight: 10
  menu_name: my-custom-menu
  class: Drupal\user\Plugin\Menu\LoginLogoutMenuLink

```

**Advanced version:**

* Copy the plugin into your `my_module/src/Plugin/Menu/` folder
* Rename it from LoginLogoutMenuLink to MyLoginLogoutMenuLink
* Update the namespace to reflect your location e.g. `namespace Drupal\my_module\Plugin\Menu;`
* In the file change `class LoginLogoutMenuLink extends MenuLinkDefault` to `class MyLoginLogoutMenuLink extends MenuLinkDefault`
* Create a `my_module.links.menu.yml` as per above but ensure you name the class as you have named it now and point it at your module. See example below.

Your `my_module/src/Plugin/Menu/MyLoginLogoutMenuLink.php` should look as follow:

```
namespace Drupal\my_module\Plugin\Menu;

use Drupal\Core\Menu\MenuLinkDefault;
use Drupal\Core\Menu\StaticMenuLinkOverridesInterface;
use Drupal\Core\Session\AccountInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * A menu link that shows "Log in" or "Log out" as appropriate.
 */
class MyLoginLogoutMenuLink extends MenuLinkDefault {
...

```

Your `my_module/my_module.links.menu.yml` should look as follow:

```
my_module.logout:
  weight: 10
  menu_name: my-custom-menu
  class: Drupal\my_module\Plugin\Menu\MyLoginLogoutMenuLink

```

I hope this helps someone.
> 3 votes

# Answer
You can do this with Bootstrap 3 Drupal 8 theme as that theme provide this feature by default. I am posting the image, of my drupal 8 trial site. One with Login page and one is with Logout page.

Are you looking such kind of thing?

*Follow following steps.*

**1.** Go to Structures\>Blocks. And make sure the following configuration in the Navigation section.

**2.** Go to Structures\>Menus\>User Account Menu and disable the My account, like shown in the following image.

So, your Main Navigation menu should show only Login and Logout, as I have posted in the first pair of image.
> 2 votes

# Answer
If you use Bootstrap subtheme you can modify this code to meet your needs:

```
<?php global $user; if ($user->uid): ?>
    <a href="/user/logout" type="button" class="navbar-brand" role="button">Logout</a>
<?php endif; ?>

<?php global $user; if (!$user->uid): ?>
    <a href="/user" type="button" class="navbar-brand" role="button">Login</a>
<?php endif; ?>

```

Put this code in **page.tpl.php** in subtheme/templates/ inside the block, where you need to:

```
< div class="navbar-header"> ... < /div>

```

I put it after the 90-line, in which case it does not collapse on a mobile device, if it is necessary that it should be folded after:

```
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

```
> 1 votes

# Answer
Programmatically, you can accomplish this via your own module's `.links.menu.yml` file. The following places these links in the "Main" menu:

```
mymodule.sign_in:
  title: 'Sign in'
  parent: system.menu.main
  description: 'Sign in'
  route_name: user.login
  weight: 100
  menu_name: main

mymodule.sign_out:
  title: 'Sign out'
  parent: system.menu.main
  description: 'Sign out'
  route_name: user.logout
  weight: 101
  menu_name: main

```

Since the "route\_name" that each of these is calling already specifies the logged in/out requirement (see https://api.drupal.org/api/drupal/core%21modules%21user%21user.routing.yml/8.4.x), the links will display depending on logged in status.
> 1 votes

---
Tags: 8, navigation
---


title: Migrate Quiz Results Data

text:
# Question
Title: Migrate Quiz Results Data
I need to "migrate" all quiz results from one website to a new one. The quiz ID is different between sites, and therefore, copying over the table from mysql won't work. However, I've made sure that user IDs are the same.

The new website isn't launched yet and there is a lot of flexibility for how I need to set things up in order to migrate in the most ideal way.

Edit: Alternatively, is there any reason I shouldn't just migrate the quizzes with the same node ID?

Edit2: I am using quiz version 7.x-5.1 on the new site but if they have to be the same, I'll have to rebuild the training feature with the version on the old site, which is 7.x-5.0-alpha4+77-dev. We have about 25 quizzes with 10-30 questions each.

# Answer
> 0 votes
This isn't the "Drupal way" to do this, but I accomplished a successful quiz results migration by making a few compromises and doing things in an unorthodox way. If anyone can build upon this and add a new answer with the correct way accomplish, I would be delighted!

The compromise I made was not allowing users to view their old results, just their score. I also decided not to use the certificate and created a view page instead for individual scores to make a certificate that way. (See this SE Post for my issues with Certificate.) This killed 2 birds with 1 stone.

Steps I followed for a successful migration trial on the test website:

1. Add quiz\_node\_results table to new database:

`mysql> insert into drupal.quiz_node_results (result_id, nid, vid, uid, time_start, time_end, released, score, is_invalid, is_evaluated, time_left) select result_id, nid, vid, uid, time_start, time_end, released, score, is_invalid, is_evaluated, time_left from drupal_web.quiz_node_results;`

2. Replaced NID of quiz results with new quiz nid, run once for each quiz (there were 18 quiz nodes):

`mysql> update quiz_node_results set nid = replace (nid, [old quiz node ID], [new quiz ID]);`

3. Removed "view quiz results" from Gradebook view (custom view I built for showing results).

Please comment with foreseeable issues with this method.

---
Tags: 7, migrations, quiz
---


title: How to get uri from Url object in twig?

text:
# Question
Title: How to get uri from Url object in twig?
I want to inject Font Awesome icons to user menu based on the route/link of each item.

But it looks like there is no way to get the path grom the url object. I tried everything I could think of but nothing worked. It's like the url object won't give any data in Twig.

This is what I am trying to do in menu template for user acocunt:

```
<li{{ item.attributes.addClass(classes) }}>
                    {% set uri = path(item.url.routeName) %}
                    <pre>{{ dump(item) }}</pre>
                    <pre>{{ dump(uri) }}</pre>
                    {% if uri == 'user' %}
                        <i class="fa fa-user"></i>
                    {% elseif uri == 'user/logout' %}
                        <i class="fa fa-sign-out"></i>
                    {% elseif uri == 'user/register' %}
                        <i class="fa fa-user-plus"></i>
                    {% elseif uri == 'user/login' %}
                        <i class="fa fa-sign-in"></i>
                    {% endif %}
                    {{ link(item.title, item.url) }}
                    {% if item.below %}
                        {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
                    {% endif %}
                </li>

```

# Answer
> 5 votes
{% set uri = item.url.toString %} will also work.

# Answer
> 3 votes
OK, so it looks like there is nothing for this in core so I had to create my own twig function.

```
<?php

/**
 * @file
 * Contains \Drupal\mymodule\TwigExtension\MymoduleTwigExtension.
 */

namespace Drupal\mymodule\TwigExtension;

use Drupal\Core\Template\TwigExtension;
use Twig_SimpleFunction;
use Drupal\Core\Url;

/**
 * My awesome twig extension.
 */
class MymoduleTwigExtension extends TwigExtension {

  /**
   * {@inheritdoc}
   */
  public function getFunctions() {
    return [
      new Twig_SimpleFunction('url_path', array($this, 'getPathFromUrl'))
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getName() {
    return 'mymodule_core';
  }

  /**
   * Gets a path from Url object.
   *
   * @param \Drupal\Core\Url $url
   *   The URL object to retrieve the path from.
   *
   * @return string
   *   Path to where the Url object is poiting to.
   */
  public function getPathFromUrl(Url $url) {
    return $url->toString();
  }

}

```

And this is the twig code:

```
<li{{ item.attributes.addClass(classes) }}>
                    {% set uri = url_path(item.url) %}
                    {% set item_title = {'#markup': item.title} %}
                    {% if uri == '/user' %}
                        {% set item_title = item_title|merge({'#prefix': '<i class="fa fa-user"></i>'}) %}
                    {% elseif uri == '/user/logout' %}
                        {% set item_title = item_title|merge({'#prefix': '<i class="fa fa-sign-out"></i>'}) %}
                    {% elseif uri == '/user/register' %}
                        {% set item_title = item_title|merge({'#prefix': '<i class="fa fa-user-plus"></i>'}) %}
                    {% elseif uri == '/user/login' %}
                        {% set item_title = item_title|merge({'#prefix': '<i class="fa fa-sign-in"></i>'}) %}
                    {% endif %}
                    {{ link(item_title, item.url) }}
                    {% if item.below %}
                        {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
                    {% endif %}
                </li>

```

**Edit:** I will change this to route names since using paths is not a good idea in d8.

---
Tags: 8, theming
---


title: How do I alter a language item link?

text:
# Question
Title: How do I alter a language item link?
I am looking to modify the default output of Drupal 8 of links in a certain situation, the language switcher. Ideally I want to be able to do that in a twig template and not have to produce a massive php file that overwwrites that whole link generation system and add a BIG if for the cases I need to overwrite.

I think the output layout should be controllable in the twig template similar to this answer (this answer outputs the same url for every languages)

I am using bootstrap as a base theme so i'd like to use the bootstrap markup for my links (btn btn-primary, dropdown)

Here is my code I am trying to make `links--language-block.html.twig`

```
{%- if links|length == 2 -%}
    {# show only alternate language button #}
    {%- for key, item in links -%}
        {%- if not item.attributes['#options']['set_active_class'] -%} {# <--- this is always true!? #}
            <a href="{{ item.link['#url'] }}" class="btn btn-primary">{{ item.link['#title'] }}</a> {# #url is always the same what ever the language it is pointing to! #}
        {%- endif -%}
    {%- endfor -%}
{%- elseif links|length > 2  -%}
    {# show selected language in button and other languages in drop down #}
    <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">{{ selectedLanguage }}<span class="caret"></span></button>
    <ul class="dropdown-menu">
        {% for key, item in links %}
            {%- if not item.attributes['#options']['set_active_class'] -%} {# <--- this is always true!? #}
            <li><a href="{{ item.link['#url'] }}">{{ item.link['#title'] }}</a></li>
            {% endif %}
        {% endfor %}
    </ul>
{%- endif -%}

```

Anyone has an idea on how to do this?

# Answer
Ok I found 2 ways to do that.

### 1. In a custom theme

You can alter variables in your `my_theme.theme` file. You need to figure out the name of the function you need. ex: `my_theme_preprocess_twig_file()`, in my case I needed `my_theme_preprocess_links__language_block()` You need to take the twig file name and replace all `-` for `_`.

`my_theme.theme`:

```
function my_theme_preprocess_links__language_block(&$variables) {
  $currentLanguageCode = \Drupal::languageManager()
    ->getCurrentLanguage()
    ->getId();
  // replace key of active language with 'activeLink'
  foreach ($variables['links'] as $i => $link) {
    /** @var \Drupal\language\Entity\ConfigurableLanguage $linkLanguage */
    $linkLanguage = $link['link']['#options']['language'];
    if ($currentLanguageCode == $linkLanguage->get('id')) {
      $variables['links']['activeLink'] = $link;
      unset($variables['links'][$i]);
    }
  }
  // if there is only 2 languages remove active one
  if (sizeof($variables['links']) == 2) {
    unset($variables['links']['activeLink']);
    // give class 'btn btn-primary' to alternate language
    /** @var \Drupal\Core\Url $alternate */
    $alternate = current($variables['links']);
    $alternate['link']['#options']['attributes']['class'][] = 'btn';
    $alternate['link']['#options']['attributes']['class'][] = 'btn-primary';
    $variables['links'] = [$alternate];
  }
}

```

### 2. In a custom module

You can also create a module that will change those same variables. There is a big difference in the values of the variables because this preprocess happened earlier in the flow. The name of the function is also quite different, ex: `my_module_api_to_modify_alter()`. In my case I needed to modify the `language_switch_links` from the `language.api.php`. You can find all alter function by searching for `*.api.php` files in drupal 8. Those are there as a reference for exactly that.

`my_module.module`:

```
function my_module_language_switch_links_alter(&$variables) {
  $currentLanguageCode = \Drupal::languageManager()
    ->getCurrentLanguage()
    ->getId();
  // replace key of active language with 'activeLink'
  foreach ($variables as $i => $link) {
    /** @var \Drupal\language\Entity\ConfigurableLanguage $linkLanguage */
    $linkLanguage = $link['language'];
    if ($currentLanguageCode == $linkLanguage->get('id')) {
      $variables['activeLink'] = $link;
      unset($variables[$i]);
    }
  }
  // if there is only 2 languages remove active one
  if (sizeof($variables) == 2) {
    unset($variables['activeLink']);
    // give class 'btn btn-primary' to alternate language
    /** @var \Drupal\Core\Url $alternate */
    $alternate = current($variables);
    $alternate['attributes']['class'][] = 'btn';
    $alternate['attributes']['class'][] = 'btn-primary';
    $variables = [$alternate];
  }
}

```

And my Twig template for both cases l`inks--language-block.html.twig`:

```
{% if links -%}
    {%- if links|length == 1 -%}
        {# show only alternate language button #}
        {{ (links|first).link }}
    {%- else -%}
        {# show selected language in button and other languages in drop down #}
        <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">{{ links['activeLink'].text }} <span class="caret"></span></button>
        <ul class="dropdown-menu">
            {% for key, item in links %}
                {% if key is not same as("activeLink") %}
                <li>{{ item.link }}</li>
                {% endif %}
            {% endfor %}
        </ul>
    {%- endif -%}
{%- endif %}

```
> 17 votes

# Answer
I made this adaption the language switcher so that when it finds a node with type article, and this is not a translation in a different langauge that it would change the link to be the homepage.

This needed to be made in a module rather than in the Theme.

I needed this as I had a massive difference in the number of translated articles per language.

```
function HOOK_language_switch_links_alter(array &$links, $type, \Drupal\Core\Url $url){
$currentLanguageCode = \Drupal::languageManager()
->getCurrentLanguage()
->getId();
// look at all links.
foreach ($links as $link) {
  // Only work on links that are not in the current page language.
  $lang_id = $link['language']->get('id');
  if ($currentLanguageCode != $lang_id) {
    // Trying to get the node.
    $node = \Drupal::request()->attributes->get('node');
    // Making sure its an object and has the method getType and is Article.
    if (!empty((object) $node)
      && method_exists($node, 'getType')
      && $node->getType() == 'article') {
      //  We know its an article, checking for languages.
      $flipped = array_flip(array_keys($node->getTranslationLanguages()));
      // Using flipped array rather than in_array
      if (!isset($flipped[$lang_id])) {
        // Translation not available.
        $links[$lang_id]['url'] = Url::fromRoute('<front>');
      }
    }
  }
 }
}

```

Don't forget to add the use statement for Drupal\Core\Url and remove it from the function arguments, its also used for the new route generation.

Also note that you have to use a new generated Url object to change the url, there is no set method for the existing url ('\<current\>') to change it.
> 1 votes

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


title: Add property to existing field type

text:
# Question
Title: Add property to existing field type
I have troubles adding a simple additional properties (like *alt* or *title*) to the image field type.

In the .module file I defined an alternative class for the image field.

```
function image_video_link_field_info_alter(&$info) {
  // Change the default widget for fields of type 'image'.
  if (isset($info['image'])) {
    $info['image']['class'] = '\Drupal\image_video_link\LinkedImageItem';
    #$info['image']['column_groups']['videolink'] = ['label' => t('Link to a video.')];
  }
}

```

I extended the `ImageItem` class with some additional properties.

```
/**
 * @file
 * Contains \Drupal\image_video_link\LinkedImageItem.
 */

namespace Drupal\image_video_link;

use Drupal\image\Plugin\Field\FieldType\ImageItem;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\TypedData\DataDefinition;

/**
 * Extends the default PathItem implementation to generate aliases.
 */
class LinkedImageItem extends ImageItem {
  /**
   * {@inheritdoc}
   */
  public static function defaultStorageSettings() {
    $settings = parent::defaultStorageSettings();
    $settings['default_image']['videolink'] = '';
    return $settings;
  }

  /**
   * {@inheritdoc}
   */
  public static function defaultFieldSettings() {
    $settings = parent::defaultFieldSettings();
    $settings['default_image']['videolink'] = '';
    return $settings;
  }

  /**
   * {@inheritdoc}
   */
  public static function schema(FieldStorageDefinitionInterface $field_definition) {
    $schema = parent::schema($field_definition);
    $schema['columns']['videolink'] = [
      'description' => "Link to a video.",
      'type' => 'varchar',
      'length' => 512,
    ];
    return $schema;
  }

  /**
   * {@inheritdoc}
   */
  public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
    $properties = parent::propertyDefinitions($field_definition);

    $properties['videolink'] = DataDefinition::create('string')
      ->setLabel(t('Videolink'))
      ->setDescription(t("Link to a video on Vimeo."));

    return $properties;
  }
}

```

I believe I have to update the database in the .install file as I am getting the following error.

> Undefined property: stdClass::$field\_gallery\_videolink

How do I do that? Is my method even valid?

# Answer
I know this is a older issue but I found it when trying to do the same. Still for this exactly case maybe answer from xxx would be also helpful.

After it took me a while to figure out how to do it I wanted to share this example. Only thing needs to change is the first few lines.

```
/**
 * Add new property to all fields of type XXX.
 */
function XXX_update_80YY() {
  $field_type = 'XXX';
  $new_properties = array(
    'PROPERTY_NAME' => array(
      'description' => 'PROPERTY DESCRIPTION',
      'type' => 'varchar',
      'length' => 255,
    ),
  );

  $definition_update_manager = \Drupal::entityDefinitionUpdateManager();
  /** @var \Drupal\Core\Entity\EntityFieldManagerInterface $field_manager */
  $field_manager = \Drupal::service('entity_field.manager');
  /** @var \Drupal\Core\Entity\EntityTypeManager $entity_type_manager */
  $entity_type_manager = \Drupal::service('entity_type.manager');
  $field_map = $field_manager->getFieldMapByFieldType($field_type);
  $schema = Database::getConnection()->schema();
  foreach ($field_map as $entity_type_id => $fields) {
    $field_manager->clearCachedFieldDefinitions();
    $storage_definitions = $field_manager->getFieldStorageDefinitions($entity_type_id);

    $storage = $entity_type_manager->getStorage($entity_type_id);
    /** @var \Drupal\Core\Entity\Sql\DefaultTableMapping $table_mapping */
    $table_mapping = $storage->getTableMapping();

    foreach ($fields as $field_name => $field) {
      $storage_definition = $storage_definitions[$field_name];
      if (!empty($storage_definition)) {
        $column_names = $table_mapping->getColumnNames($field_name);
        $table_names = [ $table_mapping->getFieldTableName($field_name) ];

        if ($storage_definition->isRevisionable()) {
          $table_names[] = $table_mapping->getDedicatedRevisionTableName($storage_definition);
        }

        foreach ($table_names as $table_name) {
          foreach ($new_properties as $property_name => $property_spec) {
            if (!$schema->fieldExists($table_name, $column_names[$property_name])) {
              $schema->addField($table_name, $column_names[$property_name], $property_spec);
            }
          }
        }
        $definition_update_manager->updateFieldStorageDefinition($storage_definition);
      }
    }
  }
}

```
> 2 votes

# Answer
you should use hook\_field\_attach\_update Hook Filed Attach Update

```
/**
 * Implements hook_field_attach_update().
*/
function mymodule_field_attach_update($entity_type, $entity) {
 // The other way around: you upload a new image on a node and enter    alt/title tags.
// Save alt and title text from the image field to the file entity,
// but ONLY if the file entity's alt/title fields are empty.
if ($entity_type == 'node') {
 list(, , $bundle) = entity_extract_ids($entity_type, $entity);
// Examine every image field instance attached to this entity's bundle.
 $instances = array_intersect_key(field_info_instances($entity_type,$bundle), _file_entity_get_fields_by_type('image'));
foreach ($instances as $field_name => $instance) {
  if (!empty($entity->{$field_name})) {
    foreach ($entity->{$field_name} as $langcode => $items) {
      foreach ($items as $delta => $item) {
        $file = file_load($item['fid']);
        if ($file) {
          if (isset($file->field_file_image_alt_text) && empty($file->field_file_image_alt_text[$langcode][0]['value'])) {
            $file->field_file_image_alt_text[$langcode][0]['value'] = $item['alt'];
          }
          if (isset($file->field_file_image_title_text) && empty($file->field_file_image_title_text[$langcode][0]['value'])) {
            $file->field_file_image_title_text[$langcode][0]['value'] = $item['title'];
          }
        }
        field_attach_update('file', $file);
      }
    }
  }
  }
 }
}

```
> 0 votes

---
Tags: 8, entities
---


# Question
Title: Where is the "Send mail to all users" action?
I installed and configured the Rules module.

When I try to add a rule like notifying a new comment to all users, I do not see the *Send mail to all users* action.

Is that normal? Is there any other module to install?

# Answer
Yes it is normal that you do NOT see "*Send mail to all users*", because there is no such Rules Action in D8 (nor in D7). In D7 there is a Rules Action like "Send an eMail to all users of a selected role", but that one is not (or not yet?) available in D8.

However, within group "*System*", there is the Rules Action "Send eMail". If you use that one, with "Send to", you can specify 1 eMail address per line. So if you enter the eMail address for each user on a single line, you have a kind of work around for what you're trying to do.

What you probably want to do later on (when the Rules module is more mature), is to use some type list of all your users, and use that list in combination with a "loop" (a typical Rules Action). If this was a D7 question, you could use the Views Rules module to create a view of all your users, and use that for such list.

With that, either you have to be patient a bit, or use the work around suggested above ...
> 1 votes

---
Tags: 8, rules
---


# Question
Title: How to change the target of a file for a multiple file field in drupal 8?
I have a content type with a file field: `field_document`.

It contains multiple files.

I chose `Generic file` as display format in `manage display` setting.

I need to change the `target` attribute of the files that drupal generates for me. How can I do that?

So instead of this

```
OUTPUT from 'core/themes/stable/templates/field/file-link.html.twig'
```

```
<span class="file file--mime-application-pdf file--application-pdf">
  <a
    href="http://somedomain.com/sites/default/files/document/2017/test_document_8.pdf"
    type="application/pdf; length=8108"
    title="test_document.pdf">Test Document</a>
</span>

```

I would need this: `target="_blank"`

```
<span class="file file--mime-application-pdf file--application-pdf">
  <a
    href="http://somedomain.com/sites/default/files/document/2017/test_document_8.pdf"
    type="application/pdf; length=8108"
    title="test_document.pdf"
    target="_blank">Test Document</a>
</span>

```

# Answer
You can do this in a hook, but also in a custom file-link template in your theme. Check if the file link has a class specific to a pdf file and then set the target attribute:

*file-link.html.twig*

```
{% if attributes.hasclass('file--application-pdf') %}
  <span{{ attributes.setAttribute('target', '_blank') }}>{{ link }}</span>
{% else %}
  <span{{ attributes }}>{{ link }}</span>
{% endif %}

```
> 2 votes

# Answer
@4k4's snippet actually just applies the attribute to the containing element, not the anchor.

You can override `template_preprocess_file_link()` in your theme and set `$options['attributes']['target'] = '_blank';`.

Related: https://www.drupal.org/node/301234
> 2 votes

---
Tags: 8, entities
---


# Question
Title: How to check if a basic page is published?
I'm using Drupal 8.1.10. I have a basic page with the URL alias "/enter-competition". On a twig template (not associated with that page), I have the following HTML:

```
<a href="/enter-competition">Enter Competition</a>

```

I need this link to only be included if that basic page is in a published state, like so:

```
{% if page_is_published %}
<a href="/enter-competition">Enter Competition</a>
{% endif %}

```

How can I check if that basic page is published/unpublished?

# Answer
> 4 votes
If you look in the core theme file `core/themes/stable/templates/content/node.html.twig` under "Available variables:" you'll find

> node.isPublished() will return whether the node is published or not.

Can also be found here.

Which means you can do:

```
{% if node.isPublished() %}
  {# content for published nodes #}
{% endif %}

```

**Edit by OP:** (17/08/2017)

The above was a partial answer, but I also had the problem that the twig file I needed do this check in wasn't associated with the node I needed to check the published state of. So, using something like `menu_get_object` wouldn't work.

Since Drupal doesn't seem to have any easy function to get a node by ID/Alias, I created the following function to get a node by URL alias:

```
public static function getPublishedStateByPageAlias($pageAlias)
{
  $nodeIsPublished = false;

  // Get node path from alias
  $path = \Drupal::service('path.alias_manager')->getPathByAlias($pageAlias);

  // If there is a valid path
  if(preg_match('/node\/(\d+)/', $path, $matches)) {
    // Get the node from the path
    $node = \Drupal\node\Entity\Node::load($matches[1]);
    // Start an entity manager
    $node_storage = \Drupal::entityManager()->getStorage('node');
    // Get the relevant node by its ID using the entity manager
    $chosenNode = $node_storage->load($node->id());

    // Is it published?
    $nodeIsPublished = $chosenNode->isPublished();
  }

  return $nodeIsPublished;
}

```

I could then call this function in my site's custom module, pass the result to the relevant twig file as a boolean variable, and conduct the necessary check.

---
Tags: views, theming
---


# Question
Title: Authenticated REST requests becoming anonymous user
I'm new to the services and rest\_server modules (and RESTful APIs altogether.) As I understand it though, the steps are basically this:

1. Send a post request to /api/user/login with the username and password set in data
2. Store the token you get in the response
3. On subsequent post requests, add the token to the header with the key X-CSRF-TOKEN

When I use the Postman Chrome extension to do that, it works great. When I do it in code, it does api/user/login fine, I get the token, but when I try to access /api/other/endpoint, I get 403 Access denied for user anonymous error.

The first request (/user/login) looks like this:

```
POST /api/user/login HTTP/1.0
Content-Type: application/json
Accept: application/json
User-Agent: Drupal (+http://drupal.org/)
Host: mysiteurl.com
Content-Length: 41

{"username":"NAME","password":"PASSWORD"}

```

And the second request (/other/endpoint) looks like this:

```
POST /api/other/endpoint HTTP/1.0
Content-Type: application/json
Accept: application/json
X-CSRF-TOKEN: vGJm5GNDGumf-SoHnLsBU6d46EkrOZkvUY0CSa08GA0
User-Agent: Drupal (+http://drupal.org/)
Host: mysiteurl.com
Content-Length: 0

```

If I make requests to /user/token after authenticating, I get new tokens each time. If I try to logout immediately after logging in (and send along that token), I get a "406 Not Acceptable : User is not logged in." error. it tells me user is not logged in.

If I check the site though, it shows the user as successfully having logged in, and still being logged in after the fact.

Do I have to save/send anything regarding the session name/id or cookie? Everything I've been looking at suggests only the session token is necessary.

# Answer
> 2 votes
(Answering my own question, and trying to sound like a third-party so it makes better sense when read...)

It looks like it definitely has something to do with the session/cookie/etc., as subsequent calls seem to be coming from a different client (from the REST server's perspective.) I'm guessing bare PHP has no way of maintaining that cookie, like how a browser would. After looking here, it looks like the cookie needs to be formatted as such in the header of the request:

```
Cookie: session_name=sessid

```

(The cookie could also be retrieved from the response's headers-\>set\_cookie variable. The latter will include all the expiration/link info in the string as well. While either method seems to work, I'm not sure if there are any ill-effects from one or the other. I just used the first method because it was the first solution I came across.)

Both session\_name and sessid can be taken from the data area of the response after a user/login request. So the request would ultimately look something like this for a user/logout

```
POST /api/user/logout HTTP/1.0
Content-Type: application/json
Accept: application/json
X-CSRF-Token: igHUQD11Y8LYdyzHi8m5t33U_tCVZNHE6BbptE4mrwQ
Cookie: SESSd3a1acd26f95229c67cd0a9a1e455bd4=rv-Kbyb8znaGlYBBU5Dn7M2GzkYdWnun5aXcVYLVfvY
User-Agent: Drupal (+http://drupal.org/)
Host: mysiteurl.com
Content-Length: 0

```

# Answer
> 0 votes
Had this same problem before when trying to login in or get the X-CSRF-Token ( /services/session/token ) via api, it just changes the token every time upon refresh or upon request. My Solution is that to set withCredentials to true before post request. After I set it, page can now read the session cookie

Example xhr.withCredentials = true;

or in my case using Vue

```
Vue.http.interceptors.push((request, next) => {
    request.credentials = true;
    next();
});

```

---
Tags: services, 8, users
---


# Question
Title: Too many redirects error with https and domain access module
I'm redirecting traffic for my various domains to HTTPS. Things seem to work fine on my local, but when I deploy to my production site I get the "www.mysite.cn redirected you too many times." error. I'm on Acquia Cloud, so I have limited access to debug apache stuff on the server.

I suspect that this may have something to do with the Domain Access module b/c we have another site with a couple domains running a multisite install (no domain access) and redirects / ssl work fine.

**Details:**

* Drupal (7.56) site running domain access (7.x-3.13) for about 10 domains for various languages (site.com, site.de, site.cn)
* Running on Acquia Cloud Professional (use of "HTTP:X-Forwarded-Proto" should handle load balancer issues)
* UCC (SAN) SSL certificate with 20 domains on it
* the .com domain (default for domain access) switches to https with no problems when deployed, all other domains give me the "too many redirects" error
* on my test environment test.mysite.com resolves to https despite the "RewriteCond %{HTTP\_HOST} !^.*test..*$ \[NC\]" condition

**Relevant code:**

.htaccess

```
#Send sites to www
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTP_HOST} !^.*devcloud.acquia-sites\.com$ [NC]
RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# Send PROD sites to https
RewriteCond %{HTTP_HOST} !^.*dev\..*$ [NC]
RewriteCond %{HTTP_HOST} !^.*test\..*$ [NC]
RewriteCond %{HTTP_HOST} !^.*local\..*$ [NC]
RewriteCond %{HTTPS} off
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

```

settings.php (standard domain access bootstrap include at the bottom)

```
// domain access
include DRUPAL_ROOT . '/sites/all/modules/contrib/domain/settings.inc';

```

# Answer
> 2 votes
Just in case anyone stumbles upon this (or perhaps for my future self). The issue ultimately ended up being Cloudflare. If you use Cloudflare for any of your domains don't forget to include it in the stack of things you're looking at when debugging (like I did).

If you use **Cloudflare**, there is a section under the "**Crypto**" menu for "**SSL**". I believe the default setting is "Flexible", if you leave this setting you can end up in a situation where you're bouncing between your load balancer and Cloudflare. The setting you want is "**Full**" once it is set to "Full" you shouldn't keep getting bounced around.

This also explains why our .com was not getting the redirect error. Our .com is the only domain not on Cloudflare b/c that DNS is out of my control

---
Tags: domain-access, ssl
---


# Question
Title: How to hook into adding watchdog entries by other modules?
Is it possible to write some code to intercept the process of adding Watchdog entries and filter them before adding to the log? Or is there a module that allows for watchdog filtering before adding to log? (I searched but nothing found) This would be useful if there are tons of well-known messages (like page not found from the same referrer or the same IP) that obfuscate the log.

# Answer
> 4 votes
Unfortunately `hook_watchdog` doesn't provide a return value which could block the insertion of the log entry in the database.

Note though that the responsible module for inserting the entry in the database is `dblog`. You could disable that and write your own implementation of it, although you'd have to replicate lots of functionality.

Another idea is to have a frequent cron job deleting the relevant log entries from the database table.

# Answer
> 2 votes
Not sure if it's still relevant, but I've made a module where you can control logging per type per level: http://drupal.org/project/watchdog\_filtering

# Answer
> 0 votes
I wrote a module that adds the needed D7 hook:

https://www.drupal.org/project/watchdogalter

> This module adds a hook\_watchdog\_alter. Used in DBLog Booster.

https://www.drupal.org/project/dblogbooster

---
Tags: 7, security, log-messages
---


# Question
Title: How to send e-mail on user account update, but not on password reset?
I want to send an e-mail after a user profile is updated but not if they are only resetting their password.

I already have the rule working so that when the user profile is updated it sends the e-mail with all the user details, but rules recognises a password reset as an account update. I don't want an e-mail to be sent if it's only a password reset.

Neither of the below rules work as expected, the first one only fires if both fields are changed, if i change the first field but not the second I get this message in the log file "Unable to evaluate condition data\_is." if I only modify the second one then I don't get the e-mail.

```
{ "rules_account_update_2" : {
    "LABEL" : "Account Update 2",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules" ],
    "ON" : [ "user_presave" ],
    "IF" : [
      { "NOT data_is" : {
          "data" : [ "account-unchanged:field-first-name" ],
          "value" : "[account:field-first-name]"
        }
      },
      { "NOT data_is" : {
          "data" : [ "account-unchanged:field-last-name" ],
          "value" : [ "account:field-last-name" ]
        }
      }
    ],
    "DO" : [
      { "mail" : {
          "to" : "",
          "subject" : "",
          "message" : "",
          "from" : "",
          "language" : [ "" ]
        }
      }
    ]
  }
}

```

The rule with an OR condition, this just never fires no matter what fields I change.

```
{ "rules_account_update_2" : {
    "LABEL" : "Account Update 2",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules" ],
    "ON" : [ "user_presave" ],
    "IF" : [
      { "NOT data_is" : {
          "data" : [ "account-unchanged:field-first-name" ],
          "value" : "[account:field-first-name]"
        }
      },
      { "OR" : [  ] },
      { "NOT data_is" : {
          "data" : [ "account-unchanged:field-last-name" ],
          "value" : [ "account:field-last-name" ]
        }
      }
    ],
    "DO" : [
      { "mail" : {
          "to" : "",
          "subject" : "",
          "message" : "",
          "from" : "",
          "language" : [ "" ]
        }
      }
    ]
  }
}

```

# Answer
> 1 votes
### 1st rule

About your 1st rule, for which you wrote in your question this:

> Neither of the below rules work as expected, the first one only fires if both fields are changed

Sorry to say, but the Rules module is working as designed ... because within your Rules Conditions, you basically specified that BOTH conditions must be satisfied.

Actually you did not specify an `AND` or an `OR`, and therefor the 2 Rules Conditions are combined with the default operator ... which is `AND`.

### 2nd rule

About your 2nd rule, for which you wrote in your question this:

> The rule with an OR condition, this just never fires no matter what fields I change.

Sorry to say (again), but the Rules module is working as designed ... because within your Rules Conditions, you basically specified that 3 conditions must ALL be satisfied, i.e.:

1. Field "first name" must be changed, AND
2. Some "empty" OR construction must be TRUE (as is shown with the line in your exported rule that looks like `{ "OR" : [ ] },` ... there is nothing between the `[ ]` in it), AND
3. Field "last name" must be changed.

Your crucial error is within that 2nd condition: you started to add on "OR" construction, but you didn't specify the 2 conditions for which that "OR" should be used. You probably thought that Rules Condition 1 and 3 are the 2 conditions to be combined with that "OR", but that is not how the Rules syntax is like (confusing, I know, many users struggle with this ...).

Therefor, try this variation of your rule (and don't forget to complete the Rules Action to actually send that eMail):

```
{ "rules_account_update_2" : {
    "LABEL" : "Account Update 2",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules" ],
    "ON" : [ "user_presave" ],
    "IF" : [
      { "OR" : [
          { "NOT data_is" : {
              "data" : [ "account-unchanged:field-first-name" ],
              "value" : "[account:field-first-name]"
            }
          },
          { "NOT data_is" : {
              "data" : [ "account-unchanged:field-last-name" ],
              "value" : [ "account:field-last-name" ]
            }
          }
        ]
      }
    ],
    "DO" : [
      { "mail" : {
          "to" : "",
          "subject" : "",
          "message" : "",
          "from" : "",
          "language" : [ "" ]
        }
      }
    ]
  }
}

```

Note the difference here: this rule has 1 Rules Condition, which is an "OR"-construct, and 2 (sub) Conditions to be combined with that "OR" are your 2 Rules Conditions about first name and last name.

BTW, when debugging / developing Rules with a Rules Action to send an eMail, I always (temporary) replace such Rules Action with just a "display a message" (like "*It works! Just rework the display of this message now to sending an eMail*").

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

# Answer
> 0 votes
Best solution: You should make use of profile2 module and make the profile separate. so you can create separate rules for entity update and user update.

other possible solution: if you have very few profile fields, make a before saving user event rule and add a rules AND condition to compare all profile field data with old data so you can know whether profile has changed or not.

* you can add the conditions on rules action section by using rules\_conditional module.

---
Tags: users, rules
---


# Question
Title: Display view results based on two values NOT matching
I am trying to filter view results based on two fields 'Workbench moderation: Latest revision ID (Latest Draft ID)' and 'Content revision: Revision ID (Published)'.

What I want to happen is if the Latest Draft ID doesn't match the Content Revision ID (Published) then it will show the fields. However if they match, it show the fields.

# Answer
> 0 votes
Solved.

I used the 'Revision translation affected' (Indicates if the last edit of a translation belongs to current revision.)

That either dumps out yes or no, set the filter to only show those with yes as an answer.

---
Tags: views, workflows, workbench
---


# Question
Title: Feed Import is successful and shows number of nodes imported but nodes not listed under content
I am using the Feeds module to import content from a different Drupal site as xml.

The problem is that the feed import is successful, and a message says how many nodes of the new content type it has created. But when I go to content or to the database the content imported is nowhere to be seen.

What is the workaround for this issue? Is it a bug in the module?

# Answer
> 0 votes
I found the solution. This is what I did for the nodes to be picked and listed under content: For the importer, Mapping for Node Processor, added a source xpathparser mapped to target GUID and checked Unique target.  Then for XPath XML parser mapped the GUID field to the Node id field in my xml file (for my case the label was Nid)

---
Tags: 6, feeds
---


# Question
Title: Do I have to set a default value to a variable in Twig
Normally in php I would have to set a default value to a variable but in Twig do I have to set a default value?

```
{% if content.my_field|render %}
  {% set offset = content.my_field['#items'].getString() %}
{% endif %}

<div{{ attributes.addClass(classes).setAttribute('data-offset', offset) }}>

```

I think it works but not sure if I should do this:

```
{% set offset = ''  %}
{% if content.my_field|render %}
  {% set offset = content.my_field['#items'].getString() %}
{% endif %}

```

# Answer
It's controlled by a Twig environment setting, `strict_variables`:

> If set to false, Twig will silently ignore invalid variables (variables and or attributes/methods that do not exist) and replace them with a null value. When set to true, Twig throws an exception instead (default to false).

Drupal doesn't change the default value, so if you also leave that setting at `false` you won't need to make sure variables exist before referencing them. In fact, if you set it to `true` I imagine quite a few core and contrib would start throwing exceptions.
> 4 votes

# Answer
I would suspect no since our variable is set only IF the rendered field has value.
> 0 votes

---
Tags: theming
---


# Question
Title: How to fix weird issue where images disappears, user is getting log out and AJAX doesn't work?
I have this weird site occurrence running in Drupal 7.34 FreeBSD environment which is running smooth for about 3 years until the last two days. I login as an administrator. Below is the interface.

When I click the 'My account link', it redirected me to the page below:

The background color disappears and turns into white.

When accessing and searching something in my custom forms made through custom module by clicking the search button, it produces the error below:

When logging in as a regular user, for example 'adalampayan'. If the user clicks the 'My Account' link, he can see the administrator panel with the administrator name above 'aegono' even if it is not the administrator.

In addition to that, when logged as administrator, I can see only one user in the 'People' section, when in fact I created another user 'adalampayan' which is reflected in my database. See two images below.

I did anything from clearing Drupal and browser cache, dropping the database and replacing it with newly installed Drupal tables. Replacing Drupal files to newly downloaded drupal 7.34 package. I created a local instance of this site in my work station and it is working fine. I dont know if this has to do with the network since it only occurs when uploaded in the server. If this has something to do with the .htaccess, sessions or what. Please do enlighten me since I really need to get this working. Any help would be very much appreciated. The server has undergone FreBSD upgrade after the site had the problem. I even restarted the server so many times.

**UPDATE**: I tried clearing the network cache and the background color was fixed. The list of users in people did also corresponds to the database. Remaining issue was even though the user was not the administrator , the admin panel with the administrator name still shows. The user still cant use or manipulate through to the forms, which is I think because it is confused who is login.

# Answer
Please make sure that:

* Clean URLs are enabled in the admin panel (at `/admin/config/search/clean-urls`).
* Make sure `mod_rewrite` Apache module is loaded correctly by going to *Administration » Reports » Status report » PHP section* and click *more information* (at `/admin/reports/status/php`).
* Verify `RewriteBase` value in your `.htaccess` file if you're using subdirectory.

The above suggestions are based on how your AJAX is requesting `"myid/?q=system/ajax"` (it should be `/system/ajax` or `/myid/system/ajax` if you're using subdirectory). Normally Drupal should support the version without clean URLs, however your custom code probably is not supporting this (so this is something to fix in your code, especially how you're generating links to the requests and images).

For the links for images, you should use `base_path()` followed by the path, e.g.:

```
$image_path = base_path() . "/sites/default/files/image.png";

```

This would explain why images and some of the requests aren't working properly, because Drupal accessing them via `?q=` parameter.

---

To troubleshoot this further, open *DevTools* (inspector) and check the Console tab for any request errors and validate the URLs based on the above. For AJAX error, check for *XHR requests* in Network tab and look for `/system/ajax` requests, then check the *Response*, most likely you'll see the actual error there.
> 4 votes

---
Tags: 7, users
---


title: List error after second click

text:
# Question
Title: List error after second click
in my app I have a views that retrieve a list of a certain content type which links to the specific node. When I click for the first time it's ok, app brings me to the page that shows the content but when I go back and I click on another item in the list, the page that shoud shows content goes blank.

Any idea?

Thank you, Cris.

> UPDATED ON 2017-08-18

***Page that shows the list:***

```
function list_articles_list_row(view, row, variables) {
  try {

      var title_html = "<div class='desc'><span class='nome'>" + row.nome+" "+row.cognome.charAt(0)+".</span> -  "+" "+row.title+"</div>";
       var image_html = "<div class='thumb'>"+theme('image', { path: row.img.src })+"</div>";

      var link = l('' + image_html + title_html, 'singlegiftapp/' + row.nid);
      return link;

   }
  catch (error) { console.log('list_articles_list_row - ' + error); }
}

```

***Single page item:***

```
    function single_page(nid) {
     var content = {};
      content['ite'] = {
        theme: 'jqm_item_list',
        title: '',
        items: [],
        attributes: { id: 'ite' + nid }
      };
      return content;
     }

function single_pageshow(nid) {
  var path_to_view = 'singlegiftapp/'+nid;
  views_datasource_get_view_result(path_to_view, {
    'success':function(data){

    if (data.nodes.length > 0) {
        var items = [];

        $.each(data.nodes, function(index, object){
              var row = object.node;

             var image_html = theme('image', { path: row.img.src });

               var description =
                '<h1>' + row.title + '</h1>' +
                '<p>Price suggested:  ' + row.Prezzo + '</p>' ;
               var dato = t(description+image_html);
              items.push(dato);

        });
         drupalgap_item_list_populate("#ite" + nid, items);
      }
    }

  });

}

```

***Thank you so much Tyler for your help!***

# Answer
> 1 votes
I'm also interested in your `page_callback` implementation, but I am guessing you just need to make your id for your item list be dynamic:

```
var itemListId = 'ite' + nid;

```

Then in your `pageshow`, do something like this:

```
drupalgap_item_list_populate("#ite" + nid, items);

```

DrupalGap 7 is a multi-page application, so as you navigate around previously visited pages remain in the DOM, so any `id` that you add to elements should be unique for that page. Which means typically you just need to append an entity `type/id` to the element's id, and you should be good to go.

---
Tags: javascript
---


# Question
Title: How to set validation error for specific subfield of the paragraph type?
I've got paragraphs type with two fields which I've added as a field into my vocabulary.

I've added validation function (`#validate`) into `$form` using `hook_form_FORM_ID_alter` where I'm validating values of these fields, however when I'm using the machine name of the paragraph field, all widgets are highlighted. My aim is to highlight only the one which fails.

The structure of that paragraph field (`field_sor_rule`) is like:

```
// var_dump($form_state->getValue('field_sor_rule'));
array (size=3)
  0 =>
    array (size=3)
      'subform' =>
        array (size=2)
          'field_sor_rule' =>
            array (size=5)
              0 =>
                array (size=2)
                  'value' => string '1' (length=1)
                  '_weight' => string '0' (length=1)

```

I've tried already referencing it as:

```
$form_state->setErrorByName("field_sor_rule[0][subform][field_sor_rule][0]",
  t('Please enter a valid value!'));

```

and:

```
$form_state->setErrorByName("field_sor_rule_0_subform_field_sor_rule_0]",
  t('Please enter a valid value!'));

```

but without success.

What would be a valid syntax?

# Answer
In the docs page for `setErrorByName()` we can read:

> string `$name`: The name of the form element. If the `#parents` property of your form element is `array('foo', 'bar', 'baz')` then you may set an error on `foo` or **`foo][bar][baz`**. Setting an error on 'foo' sets an error for every element where the #parents array starts with 'foo'.

We should also note the following code how it's parsed:

```
public function setErrorByName($name, $message = '') {
  // ...
      foreach ($limit_validation_errors as $section) {
        // Exploding by '][' reconstructs the element's #parents. If the
        // reconstructed #parents begin with the same keys as the specified
        // section, then the element's values are within the part of
        // $form_state->getValues() that the clicked button requires to be
        // valid, so errors for this element must be recorded. As the exploded
        // array will all be strings, we need to cast every value of the
        // section array to string.
        if (array_slice(explode('][', $name), 0, count($section)) === array_map('strval', $section)) {

```

So the mentioned element should have the following syntax:

```
$form_state->setErrorByName("field_sor_rule][0][subform][field_sor_rule][0",
  t('Please enter a valid value!'));

```
> 12 votes

# Answer
You might want to consider using Field Validation module. It's pre-release on D8 at the moment, but it was very handy when I used it on D7.
> 0 votes

# Answer
try to display error by using below method

add below namespace in ur form

```
use Symfony\Component\PropertyAccess\PropertyAccess;

```

set the error by using below method

```
 $form_state->setErrorByName('[quote_policy_no]','Can not submit with current date.');

```

and For display the error meassage

In your validate function

```
    $errors = $form_state->getErrors();
   if($errors = $form_state->getErrors()){
      $accessor = PropertyAccess::createPropertyAccessor();
       $accessor->setValue($form,'[#prefix]', '<div class="error-messages">' .$errors['[quote_policy_no]']. '</div>');
    }

```
> 0 votes

---
Tags: 8, forms, paragraphs
---


# Question
Title: Remove Block Directly From Database - Drupal 7
I created a block and put in some invalid PHP code resulted in entire site not accessible at all.

I'm fairly new to Drupal and I'm not a back-end programmer either. Much appreciated if you can provide a clear step-by-step guide on how to delete that particular block directly from the Database (PhpMyAdmin).

# Answer
> 7 votes
* Login into PHPMy Admin with admin credentials
* Search for the *block* table; in this table search for the block which you have created
* Change the value of status column form 1 to 0
* Delete all the content from the *cache\_bootstrap* table

# Answer
> 10 votes
To delete a block programmatically using the Database API, try this:

```
$module = 'block';
$delta = 1;

// Get the block id (bid) required to delete the correct block from table 'block_custom'
$result = db_select('block', 'b')
         ->fields('b', array('bid'))
         ->condition('module', $module)
         ->condition('delta', $delta)
         ->execute();
$bid = $result->fetchField();

db_delete('block_custom')
  ->condition('bid', $bid)
  ->execute();

db_delete('block')
  ->condition('module', $module)
  ->condition('delta', $delta)
  ->execute();

db_delete('block_role')
  ->condition('module', $module)
  ->condition('delta', $delta)
  ->execute();

```

When creating custom blocks through the Drupal Block UI, the module name is `block` and the `delta` value is an integer. Be sure to use the correct delta value to delete the desired block.

# Answer
> 3 votes
just use this simple query to delete the block.

```
delete from block where module = 'MODULE' and title = 'TITLE'

```

Replace *MODULE* with the name of the module creating the block, and *TITLE* with the block title.

If the block doesn't have a title, you could use only `delete from block where module = 'MODULE'`.

# Answer
> 0 votes
delete from block where delta = '\[DELTA\]';

If you created the block programmatically you should be able to recreate the delta value with the same logic you used to create it. It's the value you passed as the KEY to your blocks array for example $blocks\['myblock'\] -- myblock is the value stored in delta.

On an aside, I personally think its a good idea to prefix this name with your module prefix. When I look in my Blocks table, I can see mymodule\_myblock for my delta and there is no ambiguity.

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


title: How to create a tab using Views?

text:
# Question
Title: How to create a tab using Views?
I am using Drupal 7 and I have content type events. It has many node pages created used by events content type.Event names and years are fields in event content type. I want to create years as tabs.When clicks years(tabs)it will show all events names happened in that year. I don't know how to create tabs using views.

# Answer
> 0 votes
When creating a page view using views, it gives you the ability to assign a menu for that page, in this situation you can define all views with same parent path like `parent/view1` , `parent/view2`, then in middle box when adding menu item you can select views as `menu tab entry` while `default menu tab` can be assigned for the view you want to be shown when navigating to `parent` path.

# Answer
> 0 votes
Have a look at the quick tabs module. With that you can create a quick tab block, and show your view with different arguments as tabs.

---
Tags: views
---


# Question
Title: How to get value properly from form field?
I search the best way to get value from form field, and I would like to know if my code section below it's the only way to get value from field (`$value = $var[0]['value']`) or if it's possible to write this better:

```
/**
 * Implements hook_form_alter().
 */
function my_module_form_alter(&$form, FormStateInterface $form_state, $form_id){
  if ($form_id == 'node_bibliographie_form') {

    $form['#validate'][] = 'node_bibliographie_form_validate';

    foreach (array_keys($form['actions']) as $action) {
      if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
       $form['actions'][$action]['#submit'][] = 'my_module_bibliographie_form_submit';
      }
    }
  }
}

function my_module_bibliographie_form_submit(&$form, FormStateInterface $form_state){
  // Get the submitted entity.
  $key        = $form_state->getValue('field_key');
  $id_dossier = $form_state->getValue('field_dossier_reference');

  if (isset($id_dossier) && isset($key) &&  !empty($key) && !empty($id_dossier)) {
    kint($id_dossier[0]['target_id']);
    //ugly ?
    $collection_key = $key[0]['value'];
   }
}

```

# Answer
> 3 votes
If you need to get the value of the array you can use below method.

```
 $values = $form_state->getValue(array('name_of the array', 'key'));

```

# Answer
> 1 votes
You are getting fine the value, but I see that you can improve the use of `isset()` and `empty()`, because in your code you don't need to use both of them.

**empty()**

> Determine whether a variable is considered to be empty. A variable is considered empty if it does not exist or if its value equals FALSE. empty() does not generate a warning if the variable does not exist.

```
function my_module_bibliographie_form_submit(&$form, FormStateInterface $form_state){
  // Get the submitted entity.
  $key        = $form_state->getValue('field_key');
  $id_dossier = $form_state->getValue('field_dossier_reference');
  //You don't need isset().
  if (!empty($key) && !empty($id_dossier)) {
    kint($id_dossier[0]['target_id']);
    // Why you see this ugly ?
    $collection_key = $key[0]['value'];
   }
}

```

---
Tags: 8, forms
---


# Question
Title: Path alias creates redirect loop or redirects to the front page
When I call our sit "www.example.com/contact-us" I'm getting the following error:

> Oops, looks like this request tried to create an infinite loop. We do not allow such things here. We are a professional website!

If I call the site with "www.example.com/node/5" the contact page is displayed just fine.

When I check the path alias on /admin/config/search/path/edit/6, system path and alias are set correctly.

Another problem exists for another alias, when I call "www.example.com/staff" I'm getting redirected to the landing page "www.example.com". Once again the alias is set correctly.

We're using Drupal 7, and the i18n\_redirect and redirect modules.

# Answer
> 19 votes
Edit your page and go to **URL redirects**. Find the redirect path with the most number of count and delete it. Click save then view the page.

Let me know if that fixed your problem

# Answer
> 8 votes
**Update: Drupal issue #1796596 was committed as of Redirect 1.0-rc2 (June 2015). The correct solution for this problem now is to upgrade to the latest stable release of Redirect module, and then run database updates. Any circular redirects you have will be safely cleaned up.**

This issue came about due to a bug in the redirect module. You trigger it by changing a page's URL (or maybe just its title, if you're using pathauto) and then changing it back to what it used to be.

For example, let's say I had a page called "company" and I changed the title to "Our company" (which changed the URL alias to our-company). Then I decided I actually preferred it the first way soI edit the node again and change the title back to "Company". At that point the error message "***Oops, looks like this request tried to create an infinite loop. We do not allow such things here. We are a professional website!***" would start showing up on the Company page.

There are three ways to fix this, depending on what's easiest for you. They range in difficulty/bravery from top to bottom.

**The Drupal/PHP method**

There's a long Drupal bug on the subject: Issue #1796596 and there is a good working patch that fixes the issue in comment #124.

Hopefully this fix will soon get committed into the Redirect module up for download. However it's been over a year now with no sign of any progress on that front.

**The SQL method**

The fastest fix for the problem is with a SQL query to the database, with something like below. **BE CAREFUL** and only try this method if you know what you're doing - try it on a development copy of the site first and make sure you have a backup and test the changes right afterwards in case you need to roll back. Be extra careful and test the first query extra well if you are using i18n... Run the first query to show what would be deleted and the second to actually do the delete.

```
--Show records to be deleted:
SELECT r.rid, r.language, r.source, r.redirect
  FROM redirect r INNER JOIN url_alias u ON r.source = u.alias
         AND r.redirect = u.source AND r.language = u.language;

--Delete redirects shown in above query:
DELETE r FROM redirect r INNER JOIN url_alias u ON r.source = u.alias
         AND r.redirect = u.source AND r.language = u.language;

```

If you do not know how to apply patches or run SQL queries, then you need to fix the problem manually. Don't worry, this is actually quite easy to do (but time consuming compared to the other methods):

**The Manual Method:**

For each of the pages where the warning message displayed:

1. Edit the page
2. Scroll to the bottom of the edit form
3. Note the main URL of the page. It's shown underneath "URL path settings", e.g. "Alias: company" would mean the URL of the page is "company". You can click on the "URL Path Settings" to visit its section and confirm the URL alias if you're not sure.
4. Now click "URL redirects". The redirects to the current page will be shown. There will be at least one redirect that is the same as the URL alias you noted in step 3. It's possible more than one redirect in this list will match the URL alias.
5. Delete all redirects that are the same as the URL alias. These are the problem data that are causing the loop and the error message to be displayed.
6. Once there are no more redirects under "URL redirects" that exactly match the problem page's URL alias under URL path settings, the error message will be gone.

# Answer
> 1 votes
If we have the same redirecs to node's alias, another way to fix this error is to run a script that through all the nid (in case of nodes) and see if the alias of each node has a redirection with the same name, if any is eliminated.

```
for ($i=1; $i<=10000; $i++) {
  $alias = drupal_get_path_alias("node/" . $i);
  $redirect = redirect_load_by_source($alias);
  if ($redireccion->rid> 0) {
    redirect_page_cache_clear($redirect);
    redirect_delete($redireccion->rid);
  }
}

```

You can run this code in the option "Execute PHP Code" from development menu.

This form is similar to "The SQL method" just I execute this from Drupal and not on database.

# Answer
> 0 votes
Apply the patch over at Fix and prevent circular redirects (or wait until it makes it into the module).

# Answer
> 0 votes
Create Drush script:

```
<?php
// Set up the query using the database API
$query = db_select('redirect', 'r');
$query->join('url_alias', 'ua', 'r.redirect = ua.source AND r.source = ua.alias');
$query->fields('r', array('rid', 'redirect', 'source'));

// Execute it and fetch the results, one by one
$result = $query->execute();
$any_results = FALSE;
while($r = $result->fetchAssoc()) {
  // For each result, flag we've got at least one result, notify the CLI user
  // of what we're doing, and delete it using Redirect's own API
  $any_results = TRUE;
  drush_log(dt("Deleting unwanted redirect !r (!s -> !t)",
    array("!r" => $r['rid'], "!s" => $r['source'], "!t" => $r['redirect'])), "success");
  redirect_delete($r['rid']);
}

// No results? Report if that's the case
if (!$any_results) {
  drush_log(dt("Nothing to delete!"), "ok");
}

```

Save it to a file and run it from within your site's codebase using `drush php-script [PATH_TO_SCRIPT]`, and it will delete any redirects which clash with the URL aliases.

# Answer
> 0 votes
How can I prevent displaying the "redirect loop" error message in production server in future? I have already set error reporting "none" in this page - admin/config/development/logging

# Answer
> -2 votes
The only way after trying many patched was to open the redirect.module file and omit line #989

```
drupal_set_message('Oops, looks like this request tried to create an infinite loop. We do not allow such things here. We are a professional website!');

```

# Answer
> -2 votes
My english is no very good, but I think you do not problem read me. I have before that problem and I solved it so I removed the module REDIRECT. Regards KoZnaZna site Team - Simon

---
Tags: 7, redirection, path-aliases
---


# Question
Title: How can I show a block in a view page, excluding its paginated pages?
I want to place put a block in a view page. Let's say the *news* page, whose path is http://www.example.com/news.

The view uses pager to list the content.

>

I want a block to show up only in the very first page of the *news* page (http://www.example.com/news), excluding from paginated pages, such as *news?page=1*, *news?page=2*.

I set the visibility to only list in *news*, but the block still shows up in *news?page=1*, *news?page=2*.

How can I show a block in a view page, excluding its paginated pages?

# Answer
> 4 votes
You can also achieve the same in using following snippet, in the blocks visibility settings by turning PHP code on,

```
<?php
  $url = request_uri();
  $pos = strpos($url, "page");
  if ($pos === false && arg(0) =='news') {
    return TRUE;
   }
 ?>

```

# Answer
> 1 votes
I would check out the Context (http://drupal.org/project/context) module. Add a condition "Path" and enter in `news` just like you would on the normal blocks page.

Then, add `~news?page=*` which will exclude (the ~ indicates exclude) any pages with the "page" argument.

There might be a better way, but that's the best thing I can think of.

# Answer
> 0 votes
Instead of using PHP code in your block visibility settings (which gets stored in your database ...), to not *show the block on paginated pages* (as in your question), you can also use the Rules block visibility module for this. Here is a quote from its project page:

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

With that, and as per the "*if you can do it with Rules, you can use it to control block visibility*" above, you've reduced your question to making Rules "***check the path of the current page***". So that the block is only shown on pages with a path that **matches** "`news`" and **does NOT start with** "`news?page=`").

For an illustration of how to use this module, refer to my answer to "How to stop a Views block from displaying to admins, such as user/1?". It includes a Rules Component (in Rules export format), which you should replace by this variation of it to make it match your specific question):

```
{ "rules_show_block_on_page_with_no_url_parms" : {
    "LABEL" : "Show block on page with no url parms",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "module" : { "label" : "Module", "type" : "text" },
      "delta" : { "label" : "Delta", "type" : "text" },
      "result" : { "label" : "Result", "type" : "boolean", "parameter" : false }
    },
    "IF" : [
      { "data_is" : { "data" : [ "site:current-page:url" ], "value" : "news" } },
      { "NOT text_matches" : {
          "text" : [ "site:current-page:url" ],
          "match" : "news?page=",
          "operation" : "starts"
        }
      }
    ],
    "DO" : [ { "data_set" : { "data" : [ "result" ], "value" : "1" } } ],
    "PROVIDES VARIABLES" : [ "result" ]
  }
}

```

# Answer
> 0 votes
I am submitting another answer to fill in some info gaps that I ran into while trying to implement the solution by @KraigH and the updated solution by @gilzero (figures are in the image below, I cannot yet post more than two images).

1. Make sure you do not have your blocks enabled on the block page, those settings will conflict with the solution, @see **Figure 1**.
2. Set up a context and set your path to your view (blog in my case), @see **Figure 2**.
3. Under your actions set all the blocks for that region, including the main content region if you need to place your blocks above or between existing blocks in that section. Adding them will allow you to rearrange their order, even if they are already being displayed, @see **Figure 3**.
4. Once this is set up, you can use the code to alter them in a custom module. Make sure that your `$context->name` matches your name you set in the context module. Also I adjusted the `$paged` code to account for the cleanpager module.

```
/**
 * Implements hook_context_load_alter().
 */
function MYMODULE_context_load_alter (&$context) {

  // Whether current page is under paginated pages. e.g 'news?page=1'
  $paged = (isset ($_GET['page']) && preg_match('|^[0-9]+$|', $_GET['page']) && $_GET['page'] != '0');

  // If yes and context is the specific one:
  if ($context->name === 'exclude-blocks-from-pager' && $paged) {

    // Remove particular block placement:
    if (isset ($context->reactions['block']) && isset ($context->reactions['block']['blocks'])) {
        if (isset($context->reactions['block']['blocks']['views-blog-block_2'])) {
            unset ($context->reactions['block']['blocks']['views-blog-block_2']);
        }
        if (isset ($context->reactions['block']['blocks']['views-blog-block_3'])) {
            unset ($context->reactions['block']['blocks']['views-blog-block_3']);
        }
    }
  }
}

```

---
Tags: 7, blocks
---


# Question
Title: Adding process function in address field
I am customising address field so need to add *process* function in address field element.

If I am using following code, then its adding process function but then I am not able to call protected function which are defined in address class in address field module.

```
$info['address']['#process'][] = 'custom_feature_address_element_process';

```

If I am using following code, then its not working.

```
$info['address']['#process'][]  = array(0 => 'Drupal\customaddress\Element\CustomAddress', 1 => 'customprocessAddress');

```

# Answer
I have fixed the issue using following code.

```
$info['address']['#process'][]  = 'Drupal\custom_feature\Element\CustomFeature::customprocessAddress';

```

Naming convention was also issue.
> 1 votes

---
Tags: 8, entities
---


# Question
Title: Drupal mail, how do I set the recipient address to Nice Name?
Drupal mail is sending messages to

```
username <email@domain>

```

This looks like martin-green

I would like to specify the user name as "Martin Green ".

We have extended the user fields to include first and last names.

The email messages are constructed as follows:

```
  $result = drupal_mail(YogaHivePasses::MODULE_NAME, self::EMAIL_KEY, $userFromOrder->mail, $lang, $message);

```

There is a hook\_mail

```
function yhivepasses_mail($key, &$message, $params) {
  switch ($key) {
  case YogaHivePasses::EMAIL_KEY :
    $message['subject'] = $params['subject'];
    $message['body'] = $params['body'];

    // May not be any parameters. Parameters are mainly used to send attachments.
    if (array_key_exists('params', $params)) {
    $message['params'] = $params['params'];
  }

  foreach ($params['headers'] as $key => $value) {
    $message['headers'][$key] = $value;
  }
  break;
default:
  return;
 }
}

```

The mimemail module is installed.

# Answer
You can format email sender right before calling drupal\_mail()

```
  $name = 'Martin Green';
  $mail = 'email@domain.com';

  $from = '"' . addslashes($name) . '" <' . $mail . '>';

  $result = drupal_mail(YogaHivePasses::MODULE_NAME, self::EMAIL_KEY, $userFromOrder->mail, $lang, $message, $from);

```

or in hook\_mail()

```
function yhivepasses_mail($key, &$message, $params) {
  switch ($key) {
    case YogaHivePasses::EMAIL_KEY :
      // You can pass these variables to drupal_mail() or get them somehow.
      $name = 'Martin Green';
      $mail = 'email@domain.com';

      $message['from'] = '"' . addslashes($name) . '" <' . $mail . '>';

      $message['subject'] = $params['subject'];
      $message['body'] = $params['body'];

      // May not be any parameters.
      // Parameters are mainly used to send attachments.
      if (array_key_exists('params', $params)) {
        $message['params'] = $params['params'];
      }

      foreach ($params['headers'] as $key => $value) {
        $message['headers'][$key] = $value;
      }

      break;

    default:
      return;
  }
}

```
> 1 votes

---
Tags: emails
---


# Question
Title: What's the difference between using $this->t('text') and t('text') in a block plugin
I've noticed in many tutorials for constructing block plugins,

```
$this->t('text')

```

is used to create translatable text, especially in the block form function. However using

```
t('text')

```

doesn't produce any errors. Is there any difference between using either of these? And if there isn't, what's best practice?

# Answer
> 6 votes
To be exact on your question: there's **no difference** in internal implementation.

But as a **best practice**, you should be using `$this->t` instead of the global `t` wherever possible. If you check the function, `t` is returning a new TranslateableMarkup object.

If your class says `$this->t` is not defined, you can add the StringTranslationTrait to add the behavior or inject it as a dependency.

> Using this trait will add t() and formatPlural() methods to the class. These must be used for every translatable string, similar to how procedural code must use the global functions t() and \Drupal::translation()-\>formatPlural(). This allows string extractor tools to find translatable strings.
>
> If the class is capable of injecting services from the container, it should inject the 'string\_translation' service and assign it to $this-\>stringTranslation.

So as a best practice rule, you generally do not want to mix procedural within OOP unless completely unavoidable (e.g. native PHP functions).

# Answer
> 4 votes
The documentation for t() states:

> When possible, use the `\Drupal\Core\StringTranslation\StringTranslationTrait::t()`. Otherwise create a new `\Drupal\Core\StringTranslation\TranslatableMarkup` object directly.

It doesn't explain the reason for this, but if you look at the comment on the documentation page, it will give you a reason for using that trait method, or that class.

> Classes can be tested individually with PHPUnit, which runs without bootstrapping core, but the `t()` function is only available when core is bootstrapped.
> Using `$this->t()` and `StringTranslationTrait` allows the translation to be mocked, so the class can be tested in isolation with PHPUnit.

---
Tags: 8, blocks, plugins
---


title: How to reuse the query on a node page?

text:
# Question
Title: How to reuse the query on a node page?
I have a Views page which is a search page based on a Search API index containing a few filters. The results are rendered entities. When clicking one of the entities, I wonder if it is possible reuse the views query on that node page.

Say I only have 23 results by using certain filtering. When I click on one of the results, I want to *scroll* through the other 22 by using a pager. I have provided images of a non Drupal site that has what I want to achieve.

Possible solutions I can think of are as my title describes. Or create another similar view which only renders 1 entity which is used when clicking on one of the entities from the search results page. I would very much like to hear your input on this.

# Answer
This could be the same view, so not the node page, using a different (page-)display.

> You just change the pager to 1 per site and pass the page (querystring argument for the pager) to this next view, where you show the entity in a different view mode (maybe full).

For this you need to alter the node links in the first view. This could be done in hook\_views\_pre\_render. Like:

```
function MYMODULE_views_pre_render(&$view) {
  if ($view->name == 'NAMEOFTHEVIEW') {
    foreach($view->result as $r => $result) {
      $view->result[$r]->desired_field[][] = 'path/to/view?page=' . $r;
    }
  }
}

```

This code won't run, it's kind of a hint. You need to debug yourself ;)
> 0 votes

---
Tags: views, search, paging
---


title: Move title of a specific node

text:
# Question
Title: Move title of a specific node
What I want to do is remove the title of a specific content type from where it normally shows throughout the site and print it somewhere else in the template.

I have a custom node.tpl.php for the content type, lets call it node--custom-content-type.tpl.php and it sits within a little submodule I made for this content type and section on the website. Let's call that mycustom\_subtheme. I have also created a custom page.tpl.php, page--custom-content-type.php.

I was able to successfully re-print the title later on in the template, thanks to Aram's explanation here, by putting `<?php print $title; ?>` after `<?php print render($content); ?>`. I'm looking to find a way to remove it from it's original section just for this content type; *See screenshot below*.

Things I've tried:

* I tried the Exclude Node Title module, but as I feared, it actually renders the title null, which isn't suitable for my purpose of retaining the title but just moving it. For this reason, this post isn't what I need.
* I tried `hide($content['title']);` and `hide($title);` just to see if that would work in node--custom-content-type.tpl.php.
* I tried moving the `$title` data to something like `$title2` and then replacing `$title` with "Custom Text" but am not sophisticated enough to pull that off.
* I tried adding custom CSS to no avail (the title is H2 in my node template): `body.node-type-custom-content-type h2.title, {display: none;}`
* And finally, I even tried all the suggestions here. At the very least, copying the page.tpl.php and removing the title should have worked.

Here is a pastebin of my codes: custom node template and custom page template

Does the original `node.tpl.php` inherit the title anyway if `node--custom-content-type.tpl.php` simply doesn't mention it?

# Answer
> 0 votes
I managed to get this to work but welcome better options. I prefer not to alter the theme, but rather use a function or something else instead so that this module can stand alone and not be affected by themes and subthemes and other design team changes.

Here's what I did:

```
body.node-type-answers-question .page-title {
  visibility:hidden;
}

```

The source code of the loaded page, which is from a node content type called answers-question. I noticed that there was a "page-title" class in the h1 title. Making the visibility hidden worked for me.

---
Tags: 7, theming
---


# Question
Title: Best method of importing a large csv file with fields containing multiple values and sub-fields like paragraphs and field collections
I exported an old Drupal 7 site using the Views data export module. Now I need to import this back into my new Drupal 7 site, but some of my fields contain multiple values and fields that have sub fields in them (field collections).

* What would be the best method of importing this?
* Do I have to write my own custom module using the migrate module or use feeds?
* And how do I deal with importing data into a field collection or a field with multiple values?

# Answer
> 2 votes
You could try using Field Collection Feeds

> Provide feeds integration for field collection module.

# Answer
> 0 votes
This took a good 2 weeks to figure out. Here it is. Comment if you need advice.

I had to import 20k records and each record had some fields with multi-value along with sub-values like the ones used in field collections and paragraphs. Also I need taxonomy terms to be populated on the fly as it was importing the paragraphs.

On my new Drupal 7 site, I did the following using Paragraphs instead of field collections due to it being deprecated in the coming year or so:

* Create the content type your making with all the fields matched up to the old field.
* Create all the paragraphs that match up with the **sub-fields** and make sure to set them with proper limit values as it would error out if u limit the values to 1.
* Setup your taxonomies
* Be sure to install: https://www.drupal.org/sandbox/shaney/2862236 --- Major recoding is needed to fit how you want it to fit your data. I had to modify alot of the code there as it wasn't fully finished.
* In the feeds importer. Pick processor as Node processor and pick the content type your targeting
* Start mapping out your fields. The source column MUST match what you have in the csv. It could be in any order, it doesn't matter as it will know by the column name to target name.
* The trickiest part was the paragraph mappings as it involves formatting the data properly with properly used deliminator's if you have subfields of subfields. Below is a quick screen shot of what I have when mapping paragraph fields.
* Also I had to split up my 20k record file into 1500 records per a file. As my import was crashing if it went over 2000 records. I used the terminal command "split -l 15000 myfile.csv" to get it split up. then do each one at a time and cross your fingers it doesnt mess up.

I had to modify the paragraphs mapper to look like this. By default the mapper can only do 1 field. I just needed max 5 fields so I added them in manually. The proper way to do this is provide an add more fields functionality. I didn't get to do this as I only needed 5 fields mapped.

This is how it looks when an import is complete:

---
Tags: 7, migrations, feeds, importing-exporting, paragraphs
---


# Question
Title: PHP Errors with Drupal 8 (Shared Hosting)
Using Bitbucket, I've cloned my Drupal 8 site to my Media Temple server. It is shared hosting. Anyways, I'm getting the following php warning and error:

```
Warning: require(/nfs/c11/h04/mnt/55555/domains/domain.com/html/../vendor/autoload.php): failed to open stream: No such file or directory in /nfs/c11/h04/mnt/55555/domains/domain.com/html/autoload.php on line 17

Fatal error: require(): Failed opening required '/nfs/c11/h04/mnt/55555/domains/domain.com/html/../vendor/autoload.php' (include_path='.:/usr/local/php-7.0.6/share/pear') in /nfs/c11/h04/mnt/55555/domains/domain.com/html/autoload.php on line 17

```

This is my first time working with Drupal 8. I've done some research and troubleshooting, but I've not been able to solve the issue.

I'm actually having a similar issue with a separate D8 website on Bluehost (CPanel). Has anything run into this before? If so, what steps were taken to resolve the issue?

# Answer
Following @Clive's advice, I committed the /vendor and /core directories. The php errors shown in my initial question were resolved, but new, similar php errors appeared. After much trial and error, I discovered the Drupal VM was added some sort of configuration to the Drupal install. Whatever that configuration may be, it did not translate to the server environment. I downloaded a fresh Drupal 8 copy and manually installed it. After I pushed up the fresh files, it worked like a charm.
> 0 votes

---
Tags: 8, installation, composer
---


# Question
Title: Sub theme is affecting comments template of main theme
The sub-theme for the Answers module, `answers_theme`, messes up what comments look like and how they are configured in the main theme across the site. There is no `comments--mysubtheme.tpl.php` file. What else could be causing this issue?

I am building a custom sub-theme based on `answers_theme` which should only affect the part of the website it's designed for but it's affecting comments site-wide. To build the sub-theme, I've copied the files in `answers_theme` and changed the name of the module, updated all the hook references in the .module file, updated the .info file, etc. Everything works as I want it to except I can't figure out what part of the original sub-theme code is causing the comments of the main theme to mess up.

I tried copying the `comment.tpl.php` out of the main theme and renaming it to `comment--mysubtheme.tpl.php` within the subtheme template directory but that didn't help.

# Answer
> 1 votes
The templates are in the module, located here:

http://cgit.drupalcode.org/answers/tree/theme

If you copy those templates into your active theme, *they* become the override and you can do as you please from there.

I am not familiar with the Answers module, but if you don't want comments to show on them, you could probably edit the `node--answers.tpl.php` and remove the line that renders comments.

This line: `<?php print render($content['comments']); ?>`

That might do it.

But generally, copying templates from modules into your theme sets that as the template override if you're looking to add, remove, or modify what is being output. It is kind of rare (IMO) to have to unset theme hooks as a means of controlling or suppressing output at a template level.

# Answer
> 0 votes
Since we're not going to use comments for this feature, I removed the following code from my *custom version* of the `answers_theme.module` and the problem went away.

```
/**
 * Implements hook_preprocess_comment().
 */
 function discuss_theme_preprocess_comment(&$vars) {
  $bundle = isset($vars['elements']['#bundle']) && $vars['elements']['#bundle'];
  if ($bundle == 'comment_node_answers_answer' || $bundle == 'comment_node_answers_question') {
    $vars['theme_hook_suggestions'][] = 'comment__node_answers_theme';
  }
 }

```

---
Tags: theming, comments, 7
---


# Question
Title: how to add links to user menu, depending on user role?
I've this problem. I created some user roles on my site. So, when an user becomes actor, I create his actor page, where he can add BIO, demos and his events. Now, I want he can access his page from user menu. Do I must create some menu\_alter in a module? Actor page is a content type, so, I can make request to db.

# Answer
No need to create custom module .try this module . This module exposes configurable and extendable visibility settings for menu links. For example, if you want to create a 'My account' link that points to /user, both anonymous and registered users have access to the /user path, so both will see the link, even if anonymous users do not technically have an account. Using this module will allow you to only have your 'My account' link visible to registered users, and hide it from anonymous users.
> 1 votes

# Answer
You can just create a new menu and make it appear according to permission, role and content type. Put it in the same region as the user menu and style it as if they were one menu. The only drawback I see is that the links are not "mixed" (a link in the menu is between two of the other menu), which should be minor.
> 0 votes

---
Tags: users, navigation
---


# Question
Title: How to filter view results by currently logged-in user's (NOT AUTHOR'S) role?
I have a view which displays node titles. Each node has different role assigned. Currently no matter what role user has, he sees all the node titles. How do I filter view results, so that it would only display nodes, which has the current user's role only?

# Answer
> 0 votes
In Filter criteria, you can choose current user, with the help of which you can filter view with current logged in user.

---
Tags: views
---


# Question
Title: how to include .inc files in drupal8 in custom form
I have my custom module in drupal8.I have created a custom form.My form has many fields so i was wanted to move it to .inc files.Please can someone suggest me how and where to include my .inc file.

# Answer
You should use `FormStateInterface::loadInclude`:

> Ensures an include file is loaded whenever the form is processed.
>
> Use this function instead of `module_load_include()` from inside a form constructor or any form processing logic as it ensures that the include file is loaded whenever the form is processed. In contrast to using `module_load_include()` directly, this method makes sure the include file is correctly loaded also if the form is cached.

e.g.

```
// Load node.admin.inc from Node module.
$form_state->loadInclude('node', 'inc', 'node.admin');

```
> 3 votes

# Answer
The procedural function for include files seems still to exists `module_load_include()`, but you shouldn't use it in a form class. Normally you would refactor the code inside of the form class in multiple class methods. If you want an extra file, then create a new class and include it in your form class with an use statement. Each class has it's own file, which is autoloaded with PSR-4, see https://www.drupal.org/docs/develop/coding-standards/psr-4-namespaces-and-autoloading-in-drupal-8

A Trait is an alternative option. You would put the refactored methods in an extra Trait file, but logical the methods remain class methods and at the same time are reusable by other classes. The Traits are also autoloaded. See https://drupalize.me/blog/201503/dependency-injection-traits-drupal-8
> 2 votes

---
Tags: files
---