# Question
Title: Reset password after creating user account programmatically
I'm creating a user account programmatically using the code below (Drupal 8). Everything works well except when the user suppose to change their password via the Drupal generated 'one-time login link'. The password reset doesn't work and it seems the 'pass-reset-token' is not generated properly. What am I doing wrong?

```
public function submitForm(array &$form, FormStateInterface $form_state)
    {
        $the_user_email = $form_state->getValue('user_email');
        $the_user_name = $form_state->getValue('user_name');
        $language = \Drupal::languageManager()->getCurrentLanguage()->getId();

        $user = \Drupal\user\Entity\User::create();
        $user->setPassword(user_password());
        $user->enforceIsNew();
        $user->setEmail($the_user_email);
        $user->setUsername($the_user_name);
        $user->set("init", $the_user_email);
        $user->set("langcode", $language);
        $user->set("preferred_langcode", $language);
        $user->set("preferred_admin_langcode", $language);
        $user->addRole('price_list_users');
        $user->activate();

        //Create the account
        $user->save();

        _user_mail_notify('register_no_approval_required', $user);

        drupal_set_message($this->t('A welcome message with further instructions has been sent to your email address.'));
        $form_state->setRedirect('/price-list');
    }

```

# Answer
I guess you could utilize function user\_pass\_reset\_url of user.module to generate reset link and send it via your custom \_user\_mail\_notify function.

> Generates a unique URL for a user to log in and reset their password.
>
> **Parameters**
>
> \Drupal\user\UserInterface $account: An object containing the user account.
>
> **array $options**: (optional) A keyed array of settings. Supported options are:
>
> **langcode**: A language code to be used when generating locale-sensitive URLs. If langcode is NULL the users preferred language is used.
>
> **Return value**
>
> string A unique URL that provides a one-time log in for the user, from which they can change their password.
> 1 votes

---
Tags: users
---


# Question
Title: How to hide /node/ , /taxonomy/, /mymodule/, etc., from the URL path
I have the module Path auto installed. I would like that the user could not access the content by the URL http://www.myexample.com/**node/7** and instead would have to follow the menu and other webpage links with its alias. So if I forgot to set an alias for a content, I will be redirected to 404 or home page. The goal is to protect the "real" URLs which Drupal generates when creating content via admin and modules.

# Answer
If you set the patterns for a content type on URL aliases. You get the "Generate automatic URL alias" So you never get the node/\* urls on that content type.

You find the URL aliases section on your configuration page. Patterns is a tab there.
> 0 votes

# Answer
Using the Rules module you can implement a rule that looks similar to this:

```
{ "rules_check_url" : {
    "LABEL" : "Disallow node/* access",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "text_matches" : {
          "text" : [ "site:current-page:url" ],
          "match" : "node\/\\d+$",
          "operation" : "regex"
        }
      }
    ],
    "DO" : [
      { "drupal_message" : {
          "message" : "Sorry, URLs like [site:current-page:url] are not allowed around here ...",
          "type" : "error"
        }
      },
      { "redirect" : { "url" : "your_home_page" } }
    ]
  }
}

```

To experiment with this rule in your own site, just copy the entire Rules code above, and paste it in a new Rule in your own site, created via the "Import" function. Then further edit/refine to make it fit in your own environment (e.g the "Sorry, ..." message to be shown, and/or the `your_home_page` path in the sample rule here).
> 0 votes

---
Tags: 7, uri
---


# Question
Title: How do I redirect a controller to a particular vocabulary overview?
I want to redirect my controller to a specific vocabulary page. I redirect my controller using this code.

```
use Drupal\Core\Url;

public function importTypes() {
  $liste_types = $this->getListTypes();

    $batch = [
      'title' => t('Importation des types'),
      'operations' => [],
      'finished' => '\Drupal\zotero\Controller\ZoteroController::importOver',
    ];

    foreach ($liste_types as $type) {
      $batch['operations'][] = ['\Drupal\zotero\Controller\ZoteroController::create_term_from_zotero',[$type['localized']]];
    }

    batch_set($batch);
    return batch_process(\Url::fromInternalUri('admin/structure/taxonomy/manage/my_voca_id/overview'));
}

```

It throws this error.

> Error: Class 'Url' not found

# Answer
The error you are getting is because you are trying to access a method of the `\Url` class, but that class doesn't exist. The class you are trying to use is `\Drupal\Core\Url`, which is different from the `\Url` class. (Different namespace means different class.)
As you already added the `use Drupal\Core\Url;` line in your code, you just reference that class as in `Url::fromInternalUri()` (without `\`).

In your case, since you are already using an internal path, the last two lines of the code you are showing could simply be the following ones.

```
batch_set($batch);
return batch_process('admin/structure/taxonomy/manage/my_voca_id/overview');

```

In fact, `batch_process()` accepts two kinds of values, for the first parameter:

* A path
* A `Url` object

As example of call to `batch_process()` and redirect, see `LocaleController::checkTranslation()`, which a method of a controller defined from a module.

```
  $this->moduleHandler()->loadInclude('locale', 'inc', 'locale.compare');

  // Check translation status of all translatable project in all languages.
  // First we clear the cached list of projects. Although not strictly
  // necessary, this is helpful in case the project list is out of sync.
  locale_translation_flush_projects();
  locale_translation_check_projects();

  // Execute a batch if required. A batch is only used when remote files
  // are checked.
  if (batch_get()) {
    return batch_process('admin/reports/translations');
  }

  return $this->redirect('locale.translate_status');

```

Inside locale.routing.yml, you will notice that the path associated to the *locale.translate\_status* route is */admin/reports/translations*, the path passed to `batch_process()` in the code I am showing.

```
locale.translate_status:
  path: '/admin/reports/translations'
  defaults:
    _form: '\Drupal\locale\Form\TranslationStatusForm'
    _title: 'Available translation updates'
  requirements:
    _permission: 'translate interface'

```

Notice that, if you are calling `batch_process()`, you don't need to execute the redirect with the `redirect()` method of the controller. As you see in the code used from the Drupal core module, the call to `$this->redirect()` is necessary only if there isn't any batch to execute.
In your case, as you are adding the batch to execute in your controller method, the same method that calls `batch_process()`, checking the value returned from `batch_get()` is not necessary.
> 0 votes

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


# Question
Title: How to override registration form message
I should override registration form message "Registration successful. You are now logged in." with String Overrides module it does not work, because new text is long and every line with other style, it is in Drupal 7 I try to do it in template.php , but no my code is working. Can anyone help me?

# Answer
> 0 votes
You can check this message in hook\_init it's working for me please try this code.

```
function custom_init() {
 if (!empty($_SESSION['messages']['status'])) {
  $message_text_to_remove = "Registration successful. You are now logged in.";
  $key = array_search($message_text_to_remove, $_SESSION['messages']['status']);
   if ($key !== FALSE) {
      $_SESSION['messages']['status'][$key] = t('Greta Now your message changed');
    }
  }
 }

```

Thankyou

# Answer
> 0 votes
Maybe someone will need this, I put it in template.php

```
function THEME_form_alter(&$form, &$form_state, $form_id) {
 if($form_id == 'user_register_form') {
   $form['account']['mail']['#attributes'] = array('placeholder'=> array(t('E-mail')));
      $form['account']['name']['#prefix'] = '<div id="' . $form_id . '">';
      $form['account']['name']['#prefix']  = '<h5 class="title">'.t('Create account').'</h5>';
      $form['actions']['submit']['#suffix'] = '<span class="or">or</span><a href="'.$base_path.'/user/simple-fb-connect" class="fb_simple">CONTINUE WITH FACEBOOK</a>'.'<div class="back-to-login clearfix"><p>Already have an account?</p>' .  '<a href="/user/login" class="use-ajax login-account" data-dialog="true">LOGIN</a>';
      $form['actions']['submit']['#suffix'] .= '</div>';
       drupal_set_message(' Your message');
   }
}

```

---
Tags: status-messages
---


# Question
Title: How to get the value of a datetime when form submitted
I am writing a custom module in which i am declaring a $form element as #type=\> 'datetime'

The code for the buildForm method is

```
 $form['timesave'] = array(
    '#type' => 'datetime',
    '#title' => $this->t('Select Date and time'),
  );

```

Now my question is how do we get the value of the field on form Submit as i have to store the value in a configuration

I have tried with

```
$form_state->getValue('timesave');

```

This is giving an array some protected methods.

# Answer
You can use the method `getTimeStamp()` to store the timestamp like this :

```
$form_state->getValue('timesave')->getTimeStamp();

```

Or you can use the `format()` function to store a formatting date.

```
$form_state->getValue('timesave')->format("Y-m-d H:i:s");

```
> 2 votes

---
Tags: forms
---


# Question
Title: CKEditor Font Size and Family buttons does not appear
I tried to install CKEditor Font Size and Family on my fresh Drupal 8 install, but both buttons does not seem to show up.

1. Plugin is placed in `/libraries`
2. `CKEditor` and `CKEditor Font` modules are both activated
3. Both buttons `S` and `F` appear when I edit my content format (`Full HTML`)
4. Both buttons were added to the `Full HTML` CKEditor toolbar
5. My content use `Full HTML` format, and I am administrator
6. **But these buttons does not appear when I edit my content**

This problem is still here after a few days of development, so I'm already sure it's not cache-related.

Did I miss something in my configuration?
Thanks

# Answer
> 1 votes
For me, I put the center, left, and right align buttons in my "TOOLBAR CONFIGURATION". But You also need to add the **class** attribute to the filter to "Allowed HTML tags" at the bottom of the page.

```
<p id class> <br> <u> <s> <em> <strong> <cite> <blockquote cite> <code> <ul class type> <ol class start type> <li class> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id> <drupal-entity data-entity-type data-entity-uuid data-entity-embed-display data-entity-embed-display-settings data-align data-caption data-embed-button> <img src alt data-entity-type data-entity-uuid data-align data-caption> <a class href hreflang !href id rel target title> <table> <iframe src frameborder width height scrolling allowfullscreen> <caption> <tbody> <thead> <tfoot> <th> <td> <tr>

```

---
Tags: 8, wysiwyg
---


title: Views contextual filters url position

text:
# Question
Title: Views contextual filters url position
I was wondering if there was a way to change the url position of a view contextual filters. normally, they are at the end of the URL after the view-name but i would like to have them after the language.

ie: example.com/fr/*filter1*/*filter2*/*view-name*

# Answer
Views in D8 uses for contextual filters routes and you can't put a route parameter first in a route pattern, see Content type slug in route, how?. What you can do is aliasing. I don't know if there is a module for this, but you can build a custom path processor to change inbound and outbound the position of the route parameters in the path so that the View route does work.
> 1 votes

---
Tags: views, 8
---


title: Refresh [account:one-time-login-url]

text:
# Question
Title: Refresh [account:one-time-login-url]
I have a module that creates a new user and automatically logs

```
//set up the user fields
$fields = array(
  'name' => $login,
  'mail' => $to_insert['email'],
  'pass' => user_password(10),
  'status' => 1,
  'init' => $to_insert['email'],
  'timezone' => 'Europe/Paris',
  'roles' => array(
     DRUPAL_AUTHENTICATED_RID => 'authenticated user',
  ),
);

//the first parameter is left blank so a new user is created
$user = user_save('', $fields);
user_login_finalize();

```

However, I want to create a rule to send the information to the new user. I would use the token **\[account: one-time-login-url\]** but it does not work.

What for? How to refresh this token when I create a new user?

Thanks for your help

# Answer
You can handle this very easily in your module. Once you save the account and you have the user object just simply use \_user\_mail\_notify(). As an example:

```
 _user_mail_notify('password_reset', $account);

```

If you want to alter the email in any way you can do that with hook\_mail\_alter() from within your custom module.
> 1 votes

# Answer
The *one time login URL* token is a special token because it is not implemented by any `hook_tokens()`. This means that in the list of the tokens implemented by a module, you will never find that token.
It is a token that is expressly generated when some emails are sent to the users, such as:

* register\_no\_approval\_require
The users registered an account, and they don't need any approval
* register\_admin\_created
An admin user created an account
* password\_reset
A user asked for a password reset
* status\_activated
An account has been activated

From the code you are showing, it seems it's an administrator user creating accounts through your module. In that case, I would use the *register\_admin\_created* email, that could be sent using the following code.

```
$params['account'] = $user;
$language = user_preferred_language($user);
$mail = drupal_mail('user', 'register_admin_created', $user->mail, $language, $params);

```

The `$user` variable is the same variable you have.
> 0 votes

---
Tags: tokens, users
---


# Question
Title: How can I turn several Fields into a menu via a View?
I have 3 text Fields that I use for URLs, attached to a Panel Page. I'd like to create a menu with these URLs.

I've sort of done this with a View, by setting the Contextual Filters to use the node ID, then adding the Fields output and setting the Format to a pre-made Menu format I've used in the past. I've used Rewrite Results to make the `<a>` tag.

However, the issue is that all my fields are treated as a single menu item, not 3 individual ones.

Instead of the desired result being something like:

```
<span class="menu-item"><a href="url">Link Name</a></span>
<span class="menu-item"><a href="url">Link Name</a></span>
<span class="menu-item"><a href="url">Link Name</a></span>

```

The result I get is:

```
<span class="menu-item"><a href="url">Link Name</a><a href="url">Link Name</a><a href="url">Link Name</a></span>

```

Would anyone know how I can iterate through and Format each Field within a View?

# Answer
> 0 votes
OK, so the only way I could do this was to adjust the Features .module file to register both a theme and a CTools plugin:

```
/**
 * Implements hook_theme().
 */
function mycomponent_theme() {
  return array(
    'mycomponent_links_menu' => array(
      'path' => drupal_get_path('module', 'mycomponent') . '/templates',
      'template' => 'mycomponent_links_menu',
      'variables' => array(
        'config' => array(),
      ),
    ),
  );
}

/**
 * Implements hook_ctools_plugin_directory().
 */
function mycomponent_ctools_plugin_directory($owner, $plugin_type) {
  if ($owner === 'ctools' && $plugin_type === 'content_types') {
    return 'plugins/content_types';
  }
}

```

Then, I needed to create an .inc file (mycomponent\_links\_menu.inc) to enable me to add the menu as a component. On that file I created the plugin, , eg:

```
$plugin = array(
  'single' => TRUE,
  'title' => t('Link Menu'),
  'description' => t('Displays links.'),
  'category' => t('Mycomponent'),
  'edit form' => 'mycomponent_link_menu_panel_settings',
  'render callback' => 'mycomponent_link_menu_panel_render',
  'defaults' => array(),
  'all contexts' => TRUE,
);

```

and rendered the panel to a block, grabbing each Field from the node's array:

```
function mycomponent_link_menu_panel_render($subtype, $conf, $args, $contexts) {
  $node_context = reset($contexts);
  $block = new stdClass();

  $field_text1_items = field_get_items('node', $node_context->data, 'field_text1');
  $field_text2_items = field_get_items('node', $node_context->data, 'field_text2');
  $field_text3_items = field_get_items('node', $node_context->data, 'field_text3')

  $panel_content = array(
    '#theme' => 'mycomponent_links_menu',
    '#config' => array(
      'link_to_something' => l(t('Something'), $field_text1_items [0]['safe_value']),
      'link_to_anotherthing => l(t('Anotherthing'), $field_text2_items [0]['safe_value']),
      'link_to_somthingelse' => l(t('Invision'), $field_text3_items [0]['safe_value']),
    ),
  );

  $block->content = render($panel_content);
  return $block;
}

```

Then I created a .tpl file that actually wrapped the rendered links in HTML, eg:

```
  <li class="menu__item">
    <?php print $config['link_to_somthingelse']; ?>
  </li>

```

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


# Question
Title: Some tokens show as "missing name or description" in status report
Looking at a Drupal 7.43 maintenance project, my status report lists the following issue for Token 7.x-1.6:

```
The following tokens or token types are missing required name and/or description information:

$info['types']['date']
$info['tokens']['node']['url']
$info['tokens']['file']['size']
$info['tokens']['user']['url']
$info['tokens']['date']['custom']
The following token types are not defined but have tokens:

$info['types']['node']
$info['types']['term']
$info['types']['vocabulary']
$info['types']['file']
$info['types']['user']
$info['types']['current-user']

```

I have cleared cache a few times, hit update.php, and ran cron a handful of times. This message never goes away.

It is causing RealName to no longer work, path aliases are not being made, and page title / meta tags are not appearing (all are driven by Token).

What is causing this and how can I fix it? I am unable to replicate the issue locally with the same database and same code.

# Answer
In *my* case, the answer is related to the autoslave module: https://www.drupal.org/node/2898888

Also discussed here (not resolved), https://www.drupal.org/node/1265848#comment-12191146

Other mentions online about the PHP memory settings had no effect for me.

Hopefully this helps someone as the issue has been quite elusive.
> 0 votes

---
Tags: 7, tokens
---


title: attachment not sent

text:
# Question
Title: attachment not sent
I have 5 contact forms on site running drupal 8 with attachments enabled on each of them. The Emails are coming through fine but the attachments are not coming through. Please help. I have looked for solutions online but cant find any.

# Answer
> 0 votes
You have to write custom mail plugin that will support attachments, Drupal cannot/won't handle that on its own.

For example this is my mailgun plugin:

```
<?php

namespace Drupal\foo\Plugin\Mail;

use Drupal\Core\Mail\MailInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\Mail\MailFormatHelper;
use Mailgun\Mailgun;
use Mailgun\Messages\MessageBuilder;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use Drupal\Core\Plugin\PluginFormInterface;
use Drupal\Core\Form\FormStateInterface;

/**
 * @Mail(
 *   id = "mailgun",
 *   label = @Translation("Mailgun"),
 *   description = @Translation("Send e-mails via Mailgun service.")
 * )
 */
class MailGunMail implements MailInterface, ContainerFactoryPluginInterface, PluginFormInterface {

  use StringTranslationTrait;

  /**
   * The plugin instance id.
   *
   * @var string
   */
  protected $plugin_id;

  /**
   * The config factory service.
   *
   * @var \Drupal\Core\Config\ConfigFactoryInterface
   */
  protected $config;

  /**
   * The logger factory service.
   *
   * @var \Drupal\Core\Logger\LoggerChannelFactoryInterface
   */
  protected $logger;

  /**
   * Constructs MailgunMail object.
   *
   * @param string $plugin_id
   *   The plugin id.
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The config factory service.
   * @param \Drupal\Core\Logger\LoggerChannelFactoryInterface $logger_factory
   *   The logger factory service.
   */
  public function __construct($plugin_id, ConfigFactoryInterface $config_factory, LoggerChannelFactoryInterface $logger_factory) {
    $this->plugin_id = $plugin_id;
    $this->config = $config_factory;
    $this->logger = $logger_factory;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $plugin_id,
      $container->get('config.factory'),
      $container->get('logger.factory')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function format(array $message) {
    // Explode the recipients into array.
    $message['to'] = array_map('trim', explode(',', $message['to']));

    // Join the body array into one string.
    $message['body'] = implode("\n", $message['body']);

    return $message;
  }

  /**
   * {@inheritdoc}
   */
  public function mail(array $message) {
    $config = $this->config->get('foo.email_plugin.' . $this->plugin_id);
    $mailgun_key = $config->get('key');
    $domain = $config->get('domain');

    if (empty($mailgun_key)) {
      $this->logger->get('foo')->error('Missing Mailgun key.');
      return FALSE;
    }

    if (empty($domain)) {
      $domain = $this->config->get('foo.site')->get('domain');
    }

    $site_name = $this->config->get('system.site')->get('name');
    $mailer = new Mailgun($mailgun_key);
    $email = new MessageBuilder();

    array_map([$email, 'addToRecipient'], $message['to']);
    $email->setSubject($message['subject']);
    $email->setFromAddress(sprintf('%s <%s>', $site_name, $message['from']));
    $email->setReplyToAddress(empty($message['reply-to']) ? $message['from'] : $message['reply-to']);
    // @see https://github.com/mailgun/mailgun-php/issues/259
    $email->setHtmlBody(str_replace("\n", '<br>', $message['body']));

    // Add support for file attachments.
    if (!empty($message['attachments'])) {
      /** @var \Drupal\File\Entity\File $attachment */
      foreach ($message['attachments'] AS $attachment) {
        $email->addAttachment($attachment->getFileUri(), $attachment->label());
      }
    }

    // Note: headers are ignored on purpose.
    // Having 'from' header would cause Mailgun to halt the message with "multiple from"
    // error. Having 'reply-to' would cause two identical headers and so on.
    // All headers added by the \Drupal\Core\Mail\MailManager::doMail
    // are handled by the Mailgun service so the only think we have to care about
    // is the message content.

    try {
      $mailer->sendMessage($domain, $email->getMessage(), $email->getFiles());
      return TRUE;
    } catch (\Exception $e) {
      watchdog_exception($this->plugin_id, $e);
      return FALSE;
    }
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $config = $this->config->get('foo.email_plugin.' . $this->plugin_id);

    $form['key'] = [
      '#type' => 'textfield',
      '#title' => $this->t('API key'),
      '#default_value' => $config->get('key'),
      '#required' => TRUE
    ];

    $form['domain'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Domain'),
      '#default_value' => $config->get('domain')
    ];

    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateConfigurationForm(array &$form, FormStateInterface $form_state) {
  }

  /**
   * {@inheritdoc}
   */
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
    $config = $this->config->getEditable('foo.email_plugin.' . $this->plugin_id);
    $config->set('key', $form_state->getValue('key'));
    $config->set('domain', $form_state->getValue('domain'));
    $config->save();
  }

}

```

And of course you have to properly provide the attachments via `hook_mail`.

---
Tags: 8
---


# Question
Title: How to programmatically fetch the results of a view with facet filtering
**Setup**

* Drupal 8.2 + Views + Facets
* View `articles`
    + … with first sub-view `page_1`
    + … has facets
* View filter: `field_title`
* View facet: `field_facet` allows multiple values, e.g. `A` and `B`

**Concept**

I would like to fetch the view results programmatically by reusing the `$_GET` query values. (The `$_GET` values are serialized and stored for later usage.)

**Problem**

The results are correct when working with only non-facet filters. Facet filter values are ignored and won't be filtering the results by the provided snippet.

**Is the View working as expected?**

Yes, the view is working as expected: Filtering works when visiting the website with a HTTP client and the query `?field_title=Hello&field_facet[0]=A&field_facet[1]=B`.

**Snippet**

```
<?php

use Drupal\views\Views;

$view = Views::getView('articles');

$query = [
    // Filters results with title `Hello` as expected.
    'field_title' => 'Hello',

    // The programatically executed View ignores
    // the following facet based values for filtering.
    'field_facet' => ['A', 'B'],
];

$view->setExposedInput($query);

// bool(true)
var_dump($view->execute('page_1'));

$result = [];

/** @var Drupal\views\ResultRow $row */
foreach ($view->result as $row) {
    /** @var Drupal\search_api\Item\Item $item */
    $item = $row->_item;

    /** @var Drupal\node\Entity\Node $node */
    $node = $item->getOriginalObject()->getValue();

    $result[] = [
        'nid' => $node->id(),
        'title ($item)' => $item->getField('title')->getValues()[0],
        'title ($node)' => $node->get('title')->getValue(),
    ];
}

```

**Experiments with the REST module**

The REST module allows to create views with JSON results. Sadly, this module is also ignoring facet based filters.

**Question**

How do I inject/attach the facets to use their filters?

# Answer
Kinda old question but i just needed the same thing and here is how i did it.

```
use Drupal\views\Views;
use Symfony\Component\HttpFoundation\Request;

$view_id = 'VIEWID';
$display_id = 'rest_export_1';
$filters = [
  // Filters results with title `Hello` as expected.
  'field_title' => 'Hello',

  // The programatically executed View ignores
  // the following facet based values for filtering.
  'field_facet' => ['A', 'B'],
];

$view = Views::getView($view_id);
$view->setDisplay($display_id);

// Here comes the part that did the trick for my REST JSON request.
// Create a new request with your filters / url query and set that.
$request = new Request($filters);
$view->setRequest($request);

$view->execute();

//TMP debug the json decoded value
$view_result = \Drupal::service('renderer')->renderRoot($view->render());
$view_json_decode = json_decode($view_result);

```

The rest export view puts the exposed filter inside the view request so instead of setting the exposedfilters i made a request with the query args and it worked fine.

The documentation is missing a lot so if anyone finds a better way then let me know.
> 5 votes

---
Tags: 8, views, search
---


# Question
Title: Is Git now the only way to install Drush?
Going in circles trying to figure out the right way to install Drush on a Linux CentOS system. I have Git set up, but as I'm not planning to contribute to Drush code at the moment, it's not unambiguously clear that I should be using Git.

Some directions say to use PEAR, but when I go to the Drush project page, the directions say to get Drush 6 from Git. Tutorials I have found demo wget and PEAR, not Git. And the Git project page View says, "Use our Github project for contributing code, or reporting bugs, or requesting features," none of which applies.

Could an experienced Drupalista please answer the following?

1. Is Git now the only method of obtaining Drush? Someone asked a similar question more than a year ago when PEAR was still recommended.
2. If Git is the way to go, I have read that drush should not be installed within the website directories, so which directory is it recommended to be in when I invoke the following?

git clone --branch 7.x-5.x http://git.drupal.org/project/drush.git

I'm looking forward to using Drush. Thanks!

# Answer
> 12 votes
Drush moved to GitHub a few weeks ago. The official home is now: https://github.com/drush-ops/drush

The current preferred method is to install with composer:

```
composer global require drush/drush:6.*

```

If you are working with Drupal 8, or need a patch that hasn't been backported, then you can work with the latest version:

```
composer global require drush/drush:dev-master

```

You can also use composer to install a particular version.

You can install it manually; and normal GitHub retrievals apply. You can download the master (link is on the main page), or clone the repo locally. When you clone locally, you can checkout any tag you want.

I have it installed in my home directory, eg

```
cd ~
git clone https://github.com/drush-ops/drush.git drush

```

After, you need to run composer

```
cd ~/drush
composer install

```

I then put ~/drush/ in my `$PATH`:

```
export PS1=$PATH:~/drush/

```

Everything should work as normal.

Sidenote. Even if you don't want to contribute back, tracking your whole site with git is a great way to handle dev/live, and for backing out oopsies.

# Answer
> 8 votes
(1). Yes, you can still install Drush using pear. See the section "Installing - Pear" in the README.md, which is displayed on the project page: https://github.com/drush-ops/drush

To whit:

```
pear channel-discover pear.drush.org
pear install drush/drush

```

(2). If installing Drush from git, the best branch is 6.x, and the most recent tag is 6.0.0.

If you install from Pear as shown above, and you do -not- get Drush 6.0, please post a bug on the GitHub project. (Sorry, don't have time to fire up a VM and test the pear install right now, but it is presumed to work.)

Update: I missed the second question in (2). You can put it where you want. A lot of people put it in /usr/local/drush when doing a system-wide install. I usually install it per-user, in ~/local/drupal/drush. Just make sure that you also add the folder you use to your PATH. Like chrisjlee, I have an install script you may examine if you wish: https://github.com/greg-1-anderson/utiliscripts/blob/master/move-in

# Answer
> 3 votes
You can try out my project. It install's drush automatically for you:

https://github.com/chrisjlee/uamp-files/blob/master/drush/setup.sh

It's rather simple. It assumes you have git installed though.

# Answer
> 2 votes
The package repo versions of Drush are outdated, and there were major improvements to Drush that make it a better idea to install it from the git repo. If you're keeping Drupal up to date, you should be keeping Drush up to date with it as things can break when the two are not updated together.

Drush should be installed to /usr/local/bin or /opt on most \*nix systems. /opt may be better if you want to be able to backup and restore the installation and save your settings.

# Answer
> 2 votes
Since Version 9, Drush is installed by Composer when listed as dependency of Drupal 8. See also at docs.drush.org.

---

Instructions to install or upgrade a global Drush 8 (without using Git):

> ```
> # Browse to https://github.com/drush-ops/drush/releases and download the drush.phar attached to the latest 8.x release.
>
> # Test your install.
> php drush.phar core-status
>
> # Rename to `drush` instead of `php drush.phar`. Destination can be anywhere on $PATH.
> chmod +x drush.phar
> sudo mv drush.phar /usr/local/bin/drush
>
> # Optional. Enrich the bash startup file with completion and aliases.
> drush init
>
> ```

More detailed information can be found at docs.drush.org. There is also an instruction for a site-local installation.

# Answer
> 1 votes
On OS X/macOS I always installed it with Homebrew. It's just `brew install drush`. End of story.

Only recently since D8 was released and Composer got the state of the art I also always have it installed site-locally via `composer require drush/drush` to make use of it in Docker containers etc. for example.

---

# Drush 9 (D8.3+)

Actually since version 9 installing Drush with Composer is the one and only recommended way to install Drush:

> Drush 9 only supports one install method. It requires that your Drupal 8 site be built with Composer and Drush be listed as a dependency.

@see http://docs.drush.org/en/master/install/

---

### No Composer

What else you can do if you have no Composer on prod for example but at least have access to the command line, is to install Drush with Composer on a different machine, then upload the vendor/ directory and then access the Drush binary like that for example:

```
$ vendor/drush/drush/drush -y updb

```

# Answer
> 0 votes
Following is from https://www.drupal.org/node/2009426 :

> Below is how I install Drush on CentOS systems that have H-Sphere installed as a control panel
>
> 1 - Grab a copy of Drush and untar it in your shared folder
>
> `sudo wget --quiet -O - http://ftp.drupal.org/files/projects/drush-7.x-5.9.tar.gz | sudo tar -zxf - -C /usr/local/share`
>
> (Note, change the link above you the link to the latest version of drush on Drupal.org.)
>
> 2 - Create a symbolic link to where Drush can be found on your server
>
> `sudo ln -s /usr/local/share/drush/drush /usr/local/bin/drush`
>
> 3 - Get Drush to auto download the required "stuff"
>
> `sudo drush`
>
> Drush won't work yet as it won't know where to find php, so
>
> 4 - Open your bash\_profile file and edit the PATH line from something like this
>
> `bash_profile: PATH=/hsphere/shared/bin:/hsphere/shared/sbin:/hsphere/local/var/vpopmail/bin:/usr/local/bin:/usr/local/sbin:$PATH:$HOME/bin`
>
> to something like this (note the php path in this version):
>
> `PATH=/hsphere/shared/bin:/hsphere/shared/sbin:/hsphere/local/var/vpopmail/bin:/usr/local/bin:/usr/local/sbin:/hsphere/shared/php53/bin:$PATH:$HOME/bin`
>
> 5 - Reboot your server and YEE HAW!

---

With this instructions from the offical drupal site, there is absolut no need for git or any other 3rd party tools. Im perfectly fine with installing drush on my multi side vm that way.

# Answer
> 0 votes
Drush 9, which at the moment I am writing this answer is the master branch, only supports a single installation method: The Drupal 8 site must be built with Composer, and Drush be listed as dependency. Installing it globally is not supported anymore. Moshe Weitzman says it clearly in a comment at Drush 8.x doesn't install Drupal 8.4.x and Drush master doesn't install Drupal 8.3.x.

> Global install of Drush is no longer supported because you get errors exactly like the one described here. The install docs already don't mention it anymore. Each project needs to name Drush as a dependency. Its fine if Drush8 sites stick with the global install and Drupal 8.3-. For Drupal 8.4, they are going to need to use Drush9 as a dependency.

The documentation for the master branch also says it in a short note.

> Drush 9 (coming soon!) only supports one install method. It requires that your Drupal 8 site be built with Composer and Drush be listed as a dependency.

The note is referring to Drupal 8 because the minimum requirement for Drush 9 (which is the master branch, at this moment) is Drupal 8.3+. The Drush 8 documentation, reports the following commands as method to globally install it.

```
# Download latest stable release using the code below or browse to github.com/drush-ops/drush/releases.
wget http://files.drush.org/drush.phar

# Test your install.
php drush.phar core-status

# Rename to `drush` instead of `php drush.phar`. Destination can be anywhere on $PATH.
chmod +x drush.phar
sudo mv drush.phar /usr/local/bin/drush

# Optional. Enrich the bash startup file with completion and aliases.
drush init

```

---
Tags: drush
---


# Question
Title: What is the node:id cache tag equivalent for blocks?
I am wondering why the last two entries do not work:

```
public function getCacheTags() {
  $tags = [
    'node:270',
    'node:271',
    'node:273',
    'node:282',
    'block:customblockname',
    'block:7',
  ];
  $cacheTags = Cache::mergeTags(parent::getCacheTags(), $tags);

  return $cacheTags;
}

```

When I edit my custom block the URL is:

> /block/7?destination=/admin/structure/block/block-content

The actual id of the block (for instance when embedding it) is `customblockname`.

What are the correct cache tags to include that block in my caching?

# Answer
> 1 votes
I just figured myself. The cache tag for custom blocks is simply:

`block_content:7`

---
Tags: 8, blocks, caching
---


# Question
Title: Add CSS class to <form> element using webform and template file
I have an existing webform in Drupal 7 which I am trying to theme. So far I managed to add CSS classes, placeholders, prefix, suffix,.. to form *elements* (fields) but not to the actual `<form>`-tag?

I tried this:

```
$form['#attributes']['class'][] = 'form-horizontal';`

```

But that didn't change anything to the output.

edit: I have found that putting `var_dump($form['#attributes']);` displays the array below the form-tag. Does that mean that you cannot alter the root element inside a template file (webform-form-8.tpl.php) and that I should implement the hook in template.php?

# Answer
I believe your edit is correct. You should add the class in a preprocessor function within template.php.

A similar question and answer can be found here.
> 0 votes

# Answer
```
function THEME_form_alter(&$form, &$form_state, $form_id) {
    $form['#attributes']['class'][] = 'my_class';
}

```

in a template.php
> 0 votes

---
Tags: theming, webforms
---


# Question
Title: On Ajax submit, vars added in preprocess are lost
I'm currently working on a D8 project and I'm displaying a node edit form in a block. I use template\_preprocess\_table in order to pass some parameters to my theme but when I submit the form using ajax the form is reloaded and the parameters are lost so I don't get the correct form format.

Update:

In my MYTHEME.theme file:

```
function MYTHEME_preprocess_table(&$variables) {

  if($variables['attributes']['id'] == 'field-completion-milestones-values'){
    $element = $variables['rows'];
    foreach( $element as $key => $milestones){
      $completion_milestone = $milestones['cells'][1]['content'];

      if(isset($completion_milestone['field_milestone'])){

        $milestone_id = $completion_milestone['field_milestone']['widget']['#default_value'][0];
        $default_completion_milestone = array('name' => $milestone_id);
        $type_id = milestoneGetTypeId($default_completion_milestone);
        if($type_id == 156) {//Milestones with links - create button
          $variables['rows'][$key]['cells'][1]['content']['test_button'] = TRUE;
        }
        else if($type_id == 155){//Milestones with upload document button
          $variables['rows'][$key]['cells'][1]['content']['test_upload'] = TRUE;
        }
        else if($type_id == 154){//Milestones without link or upload buttons
          $variables['rows'][$key]['cells'][1]['content']['test_plain'] = TRUE;
        }
      }
    }
  }
}

```

And in my table.html.twig file:

```
{% set milestone_id = cell.content.field_milestone['widget']['#default_value'][0] %}
{% if(milestone_id) %}
    <div class="delivery__completed-milestones__field">
      <label>{{ cell.content.field_milestone['widget']['#options'][milestone_id] }}</label>
        <span class="status-marker delayed">D</span>
        {% if cell.content.field_tip['widget'][0]['value']['#default_value'] %}
            <span class="custom-tooltip"><span title="{{ cell.content.field_tip['widget'][0]['value']['#default_value'] }}">?</span></span>
        {% endif %}
        {% if cell.content.test_button %}
             {% set custom_url = cell.content.field_url['widget'][0]['uri']['#default_value'] %}
             {% if cell.content.field_url['widget'][0]['title']['#default_value'] %}
                 {% set link_text = cell.content.field_url['widget'][0]['title']['#default_value'] %}
             {% else %}
                 {% set link_text = cell.content.field_url['widget'][0]['uri']['#default_value'] %}
             {% endif %}
             <a class="button" href ="{{ custom_url }}">{{ link_text }}</a>
        {% endif %}
        {% if cell.content.test_upload %}
             {{ cell.content.field_milestone_completion_up }}
        {% endif %}
        <div class="hidden">
           {{ cell.content.field_delivery_status }}
        </div>
    </div>
{% endif %}

```

My form submit function:

```
public static function ajaxFormEntityFormSubmit($form, &$form_state) {
    $entity = $form_state->getBuildInfo()['callback_object']->getEntity();

    // Clear user input.
    $input = $form_state->getUserInput();
    // We should not clear the system items from the user input.
    $clean_keys = $form_state->getCleanValueKeys();
    $clean_keys[] = 'ajax_page_state';
    foreach ($input as $key => $item) {
      if (!in_array($key, $clean_keys) && substr($key, 0, 1) !== '_') {
        unset($input[$key]);
      }
    }

    // Store new entity for display in the AJAX callback.
    $input['entity'] = $entity;
    $form_state->setUserInput($input);

    // Rebuild the form state values.
    $form_state->setRebuild();
    $form_state->setStorage([]);
  }

```

And my callback:

```
public static function ajaxFormEntityCallback(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
    // If errors, returns the form with errors and messages.
    if ($form_state->hasAnyErrors()) {
      return $form;
    }
    // Else show the result.
    else {
      $userInputs = $form_state->getUserInput();
      $entity = $userInputs['entity'];
      $entity_type = $entity->getEntityTypeId();
      $configurations = $form_state->getValue('ajax_form_entity');

      $response = new AjaxResponse();

      // Get messages even if not shown.
      $status_messages = array('#type' => 'status_messages');
      $message = \Drupal::service('renderer')->renderRoot($status_messages);

      // Reload the form.
        $response->addCommand(new ReplaceCommand($configurations['form_selector'], $form));

      return $response;
    }
  }

```

In my hook\_form\_alter :

```
    $form['#attributes']['class'][] = $ajax_id;
    $form['actions']['submit']['#submit'][] = 'Drupal\MY_MODULE\Plugin\Form\FormAlter::ajaxFormEntityFormSubmit';
    $form['actions']['submit']['#ajax'] = array(
      'callback' => 'Drupal\MY_MODULE\Plugin\Form\FormAlter::ajaxFormEntityCallback',
      'wrapper' => $ajax_id,
      'effect' => 'fade',
    );
    $form['ajax_form_entity'] = [
      '#type' => 'hidden',
      '#value' => [
        'reload' => '.reload',
        'form_selector' => '.' . $ajax_id,
        'show_message' => TRUE,
      ]
    ];

```

What I'm doing is to show/hide fields from a field collection field based on a taxonomy term value. Maybe this is not the best solution but I didn't find any other way to solve my problem.

Is it possible to store those vars somehow after ajax submit?

Thanks in advance.

# Answer
I managed to solve this without using template\_preprocess\_table. Instead I used created a custom module where I extend the twig in oder to have access to a function in my PHP. In my Twig I call that function and I get as a return the values so as I can display properly the fields needed.
> 0 votes

---
Tags: 8, ajax
---


# Question
Title: How to display current langage on top of the langage list in a content type
I am using **drupal 7.54** and I am a bit in trouble.

I have made a multilingual website based on **entity translation**.

I created a **custom content type** that users can create or edit nodes with. And that content type has a **language field**.

But in that dropdown field, **English shows first in both languages**. It confuses french users. So I need to **make the current language the first on the list of languages**. As an example I want the list to display like this

* Français
* Anglais

when viewing the site in **French** version. And :

* English
* French

when viewing the site in **English**.

Hopefully I explained the problem properly, I'll be very happy to know what to do.

I need help please.

# Answer
> 1 votes
If you edit your content type, you should have a `Language settings` tab, I guess you have on Default Language "Site's default" and not the current interface language.

---
Tags: nodes, i18n-l10n
---


# Question
Title: Images are uploaded to a different directory than shown in the background:URL style
We've just had to take over the hosting for a Drupal site and I've moved the site across and everything seemed OK. BUT, whenever I try to upload a new image it gets saved in a different directory to where it should.

So the background:URL("") inline style is looking for the image here: /sites/default/files/styles/segment\_background\_image/public/file.jpg

When the file is actually saved here: /sites/default/files/file.jpg

I know absolutely nothing about Drupal and reading other peoples issues is just hours of not understanding a word. Any help would be hugely appreciated.

EDIT: To be more specific, the image doesn't display on the site because the inline style is looking in the wrong directory. It's an inline style, background:url("path"), where the path is different to where it is actually saved.

# Answer
That's all correct, you don't need to change anything.

Images under /sites/default/files/styles are *derivatives*, auto-generated by the system from image styles when first requested.
> 2 votes

# Answer
It was all to do with the new server and it's PHP.ini. Not enough memory, upped that and all of my problems were solved.

Thanks for helping though, confirmed that Drupal was working as it should!
> 0 votes

---
Tags: media, uri
---


title: Submit handler does not work

text:
# Question
Title: Submit handler does not work
I am trying to handle multiple submit buttons, but the handlers does not get called.

I am following http://www.hooksupport.com/blog/drupal-8-how-handle-multiple-submission-buttons-drupal-8-form, and this is the code I am using.

```
$form['add_field'] = array
    (
      '#type' => 'submit',
      '#value' => $this->t('Create field'),
      '#submit' => array('::create_field_submit'),
    );

 public function create_field_submit(array &$form, FormStateInterface $form_state){
     drupal_set_message(t('Form Submitted Successfully'), 'status', TRUE);
}

```

The message I've trying to send does not appear. Why?

# Answer
> 0 votes
If this is not working, then the reason for this is, that the block plugin is not the form class. This is `BlockForm`, which calls the methods in the plugin while building, validating and submitting the form. So if you want to add custom code to the submit in a block plugin override:

```
public function blockSubmit($form, FormStateInterface $form_state) {}

```

This code will then be included when the form class calls `submitConfigurationForm()`.

If you have more than one submit button you can check the triggering element in `$form_state`.

---

Edit:

Another option is to use a static submit function instead of the class method.

# Answer
> 0 votes
`'::create_field_submit'` doesn't mean *use the `create_field_submit()` method of the class containing the code I am using*. For `FormState::prepareCallback()`, the method handling such handlers, it means *Use the `create_field_submit()` method of the object returned from `FormState::getFormObject()`*.

```
public function prepareCallback($callback) {
  if (is_string($callback) && substr($callback, 0, 2) == '::') {
    $callback = [$this->getFormObject(), substr($callback, 2)];
  }
  return $callback;
}

```

Given that `FormState::getFormObject()` declares its returned value to be an object implementing `\Drupal\Core\Form\FormInterface`, this limits its possible usage to few classes, which doesn't include a block plugin, which doesn't implement that interface.

As Clive said, try with `[$this, 'create_field_submit']`, and see if it works.

---
Tags: forms
---


# Question
Title: How to disable module warning "User warning: The following module is missing from the file system" only visible on update.php?
I have a warning when using the update.php. This warning is not visible when using : drush cc all

> User warning: The following module is missing from the file system: aaa. For information about how to fix this, see the documentation page. in \_drupal\_trigger\_error\_with\_delayed\_logging() (line 1128 of C:\www\arlande.nl\includes\bootstrap.inc).

I did run all solutions basis on : https://www.drupal.org/node/2487215

Finally I found out: There is a record in the system table. If I delete this line using drupal it is oke and the warning is gone.

However when I use update.php script again the warning is there again and also the record is again available in the system table.

Information in the system table is indicating: The type is a module again but the file reference is not in modules but in profile.

> profiles/aaa/aaa.profile

Big change this is profile of the initial installer but is not there any more and I'm not able to get this anymore.

I scanned all code to see if a hook is used but that 100% not the case, so the reference should come from somewhere inside the database.

Any suggestion where the update.php file is getting this reference from in the database and/or how to solve this?

# Answer
> 1 votes
Probably you haven't uninstalled the module, so you've to either:

* restore the module to its original location and uninstall it,
* or manually remove all traces of the module in the database (not recommended) by:

+ using Module Missing Message Fixer (Drupal 7)
    + using Drush command:

    - Drupal 7

        ```
        drush sql-query "DELETE from system where name = 'old_module1' AND type = 'module';"

        ```
        - Drupal 8

        ```
        drush sql-query "DELETE FROM key_value WHERE collection='system.schema' AND name='module_name';"

        ```

        When it's done, clear the site's caches: `drush cr`.

        Or use Devel module by going to: `/devel/php` and execute:

        ```
        $query = \Drupal::database()->delete('key_value')
              ->condition('collection', 'system.schema')
              ->condition('name', 'module_name')
              ->execute();

        ```

See: How to fix "The following module is missing from the file system..." warning messages.

---
Tags: 7
---


# Question
Title: How to add a button "Add More" with ajax for adding multiple fields?
I want to add a button "Add More" with ajax for adding multiple fields I have writed this code, I don't understand why when I click to "add more" nothing work, there is an solution?

this is my code:

```
function produits_add($form, &$form_submit){

        if(!isset($form_state['num_names'])){
            $form_state['num_names']=1;
        }

        // Create wrapper for ajax
        $form['#prefix'] = '<div id="form-wrapper">';
        $form['#suffix'] = '</div>';

        for ($i = 0; $i < $form_state['num_names']; $i++) {

            $form['name_' . $i] = array(
                '#type' => 'textfield',
                '#title' => t('Name')

            );
        }

        $form['add_button']= array(
            '#type' => 'button',
            '#value'=> 'Add more',
            '#ajax' => array(
                'callback' => 'ajax_add_col',
                'method' => 'replace',
                'effect' => 'fade',
                'wrapper' => 'form-wrapper',
            ),
        );

        $form['submit'] = array(
            '#type' => 'submit',
            '#value' => 'Submit',
            '#submit' => array('produits_add_submit'),
        );

        return $form;
    }

    function ajax_add_col($form, &$form_state){

        $form_state['num_names']++;

        // rebuild whole form with new values
        $form_state['rebuild'] = true;
    }

function produits_add_submit($form, &$form_state){

// Some code
}

```

# Answer
In your form function, group the textfields under a key, you can define your own key. I use `group` here.

```
// Create wrapper for ajax
$form['group']['#prefix'] = '<div id="form-wrapper">';
$form['group']['#suffix'] = '</div>';

for ($i = 0; $i < $form_state['num_names']; $i++) {

  $form['group']['name_' . $i] = array(
    '#type' => 'textfield',
    '#title' => t('Name')
  );
}

```

In your ajax callback, return part of the form.

```
function ajax_add_col($form, &$form_state){

  $form_state['num_names']++;

  // rebuild whole form with new values
  $form_state['rebuild'] = true;

  return $form['group'];
}

```
> 1 votes

# Answer
If anyone is still having this problem, like above please change your button type to submit. `$form['add_button']= array(
 '#type' => 'button',
 '#value'=> 'Add more',
 '#ajax' => array(
 'callback' => 'ajax_add_col',
 'method' => 'replace',
 'effect' => 'fade',
 'wrapper' => 'form-wrapper',
 ),
 );`

---

# Change to

`$form['add_button']= array(
 '#type' => 'submit', //change this submit
 '#value'=> 'Add more',
 '#submit' => array('ajax_example_add_more_add_one'),//add this to handle
 //your increment and rebuild form
 '#ajax' => array(
 'callback' => 'ajax_add_col',
 'wrapper' => 'form-wrapper',//returns the fieldset
 ),
 );`
> 0 votes

---
Tags: 7, forms, hooks, ajax
---


# Question
Title: Unanswered Questions only show for admins
I am using the Answers module to configure a discussion feature on our website. The view, which shows the list of questions as well as answers, is only showing questions which have been answers but not unanswered questions, except for admins, who can see all of them. Once the question is clicked, any user can provide an answer.

I cloned, edited and disabled the original view. I've made sure that all authenticated users are able to view published nodes, create questions and add answers.

I've installed this module in a separate sandbox site which is completely stripped to the bare bones and it works as designed, everyone can see all questions.

Customizations I have made to the view include, changing from table to unformatted list format, and bringing in various fields. This screenshot shows the version I created which populates the view with questions and answers, however, this issue was going on before I made that customization.

I'm using Answers version 7.x-4.0-rc2

**Edit**: I have installed this module in a fresh sandbox with no customizations and it works perfectly so I know it's something I broke.

See the exported view. Note "Debugging page" is a simplified version that still has the problem. Please use that page when debugging.

# Answer
This issue was solved by taking the advice here and disabling SQL rewriting in the query settings of the view. There is a conflict with some sort of access or workbench module. I haven't been able to pinpoint which one.
> 0 votes

# Answer
Apart from the customizations you described (within your "customizations I have made ..."), you also seem to have customized the 2nd (last) filter that you're using: it says "(in Answered ...)", while in your exported view it shows the machine names of content type "Question" *and* content type "Answer". While the view shipped with the Answers module (disclosure: I'm a co-maintainer of it) uses ONLY the "Question" content type.

I suggest you adapt that 2nd filter back to how the shipped version looks like, i.e make that filter only check for nodes of content type "Question". And if you then need any other data (columns in your view) specific to the "Answer" content type, those should be made available via the 1st relationship (entity reference) you already have in place (and which still matches the shipped version).

I'm not yet sure if this is the only change you'll need, but at least it will get you closer to the view you're trying to create (depending on possible updates to your question, I might further improve my answer afterwards).

PS: I noticed you also turned of "aggregation" (another customization). Not sure (yet) if that has anything to do with your issue.
> 0 votes

---
Tags: views, 7
---


# Question
Title: How to access all of the properties related to Commerce Line Item entity in a rule?
I wonder how I can access all of the line item properties in Rules?

For example in a Rules event "Before saving a line item" I can show a debug message of the line item. It has different properties such as **commerce\_display\_path** and **data-\>context-\>entity** which however aren't available in Rules ie. I cannot set them as variable for later processing.

How could I make these properties available to Rules? I've tried to add different conditions to make sure the "whole entity" is loaded to Rules but still I cannot access these properties.

**EDIT 1**

I've now tried to develop a solution to provide this data to Rules. Following enables only entity(field collection item) id and entity revision and nothing else. I thought that it would provide the whole entity and it's properties (or at least so I understood from documentation that all that entity\__property\_info returns).

**EDIT 2**

Now I can set a message on site that presents host entity properties. However, I cannot use those properties in any other rules functionality eg. I cannot create variable from field regarding field collection item i.e. I still cannot make use of them. Why the properties are available for message but not for anything else?

```
function mymodule_entity_property_info_alter(&$info)
{
  if (isset($info['commerce_line_item'])) {
    $info['commerce_line_item']['properties']['host_entity'] = array(
      'label' => 'Host entity',
      'type' => 'field_collection_item',
      'description' => t('Host entity of a line item.'),
      'getter callback' => 'mymodule_get_host_entity_callback',
      'setter callback' => 'entity_property_verbatim_set',
      'computed' => true,

    );

 $bundles['field_collection_item'] = array('label'=>'Field collection item', 'properties'=>entity_get_all_property_info('field_collection_item'));
    dpm($info['commerce_line_item'], 'line item in entity info alter');
  }
}

function mymodule_get_host_entity_callback($entity, array $options, $name, $entity_type)
{
  dpm($entity, 'line item entity in Rules callback');
  $wrapper = entity_metadata_wrapper($entity_type, $entity);

  $host_entity_id = $wrapper->data->context->entity->entity_id->value();
  $host_entity_type = $wrapper->data->context->entity->entity_type->value();

  $host_wrapper = entity_metadata_wrapper($host_entity_type, $host_entity_id);
  $host = $host_wrapper->value();

  return $host;
}

function mymodule_set_host_entity_callback($entity, array $options, $name, $entity_type)
{
  $wrapper = entity_metadata_wrapper($entity_type, $entity);

  return $wrapper->host_entity->value();
}

```

# Answer
> 0 votes
Below is a possible approach you can use to solve your question. It provides the details about how I was able to have a set of Drupal messages being shown at checkout time, which look similar to this testcase I used (for a cart with 3 line items):

```
Current line item has label 'USB-BLU-08' and id '17'
Current line item has label 'TSH4-BLK-MD' and id '18'
Current line item has label 'MES1-BLU-OS' and id '19'

```

To get this to work, I created a custom rule, which looks like so (use the Rules UI to import it in your own site):

```
{ "rules_access_line_items_at_checkout" : {
    "LABEL" : "Access line items at checkout",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "commerce_checkout" ],
    "ON" : { "commerce_checkout_complete" : [] },
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "commerce-order:commerce-line-items" ] },
          "ITEM" : { "line_item" : "Current line item" },
          "DO" : [
            { "drupal_message" : { "message" : "Current line item has label \u0027[line-item:line-item-label]\u0027 and id \u0027[line-item:line-item-id]\u0027" } }
          ]
        }
      }
    ]
  }
}

```

Some details about it:

* Rules Event: After completing the checkout process.
* Rules Condition: none.
* Rules Action: Create a loop, to iterate over each line item. And for each line item, show a Drupal message, starting with "Current line item has ...". Obviously, at this point you could display any of the properties related to a line item.

***Easy, no?***

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

# Answer
> 0 votes
There was no answer for using "API functions" and the only way to solve this was to add extra functionality to Rules via custom module.

I had to provide new data to Rules and use it in the event of "Calculate sell price". I'm not sure that if I could have triggered this event programmatically or something similar but at least now it works.

---
Tags: commerce, rules, debugging
---


title: How do you print View fields on Twig?

text:
# Question
Title: How do you print View fields on Twig?
I have a view and added the title as a field.

For example: How do I print the title?

> In Drupal 7 it was as simple as
>
> **views-view-fields--\[viewname\].tpl.php**
>
> ```
> <?php print $fields["title"]->content; ?>
>
> ```

### How do we do this in Drupal 8?

I have created **views-view-fields--\[viewname\].html.twig**

I thought it might be `{{ fields.title }}` but I get the classic error message like so:

> The website encountered an unexpected error. Please try again later.

I then tried `{{ field.title }}`, `{{ title }}` and `{{ content.title }}` but nothing prints.

# Answer
> 13 votes
After eating dinner, washing the dishes, playing around with it and reading the comments in **views-view-fields.html.twig** located in `core\modules\views\templates`

```
/**
 * @file
 * Theme override to display all the fields in a row.
 *
 * Available variables:
 * - view: The view in use.
 * - fields: A list of fields, each one contains:
 *   - content: The output of the field.
 *   - raw: The raw data for the field, if it exists. This is NOT output safe.
 *   - class: The safe class ID to use.
 *   - handler: The Views field handler controlling this field.
 *   - inline: Whether or not the field should be inline.
 *   - wrapper_element: An HTML element for a wrapper.
 *   - wrapper_attributes: List of attributes for wrapper element.
 *   - separator: An optional separator that may appear before a field.
 *   - label: The field's label text.
 *   - label_element: An HTML element for a label wrapper.
 *   - label_attributes: List of attributes for label wrapper.
 *   - label_suffix: Colon after the label.
 *   - element_type: An HTML element for the field content.
 *   - element_attributes: List of attributes for HTML element for field content.
 *   - has_label_colon: A boolean indicating whether to display a colon after
 *     the label.
 *   - element_type: An HTML element for the field content.
 *   - element_attributes: List of attributes for HTML element for field content.
 * - row: The raw result from the query, with all data it fetched.
 *
 * @see template_preprocess_views_view_fields()
 */

```

`{{ fields.title.content }}` worked for me. In hindsight it's very similar to the D7 code, duh, lol.

For other fields:

`{{ fields.machine_name.content }}` What's the machine name? You can find them under the Machine Name column in the Manage Fields of your content type or block.

# Answer
> 3 votes
I have figured a way using kint.

Inside your views-view-unformatted.html.twig use the following code to display your individual fields:

```
{% for row in rows %}

{{ row.content['#view'].style_plugin.render_tokens[ loop.index0 ]['{{ YOUR_FIELD_NAME }}'] }}

{% endfor %}

```

# Answer
> -1 votes
An easier way to do this is to install HTML Field Formatter

Then, go to your field display settings and pick the new HTML formatter. It works with Views in D8, too

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


# Question
Title: Form block: how to choose which fields are being displayed?
I created a form block using the form block module to allow users to post a certain content type and fill out the form without leaving the page. I don't remember how I chose which fields to show. Currently it only shows the title and the submit button but I would like to add another field and change the label of the button. Can I do that with this module and if so, how? Thanks!

# Answer
> 1 votes
I needed to adjust custom field permissions for the field I wanted to show and once I set the field permissions to "public" they showed. The permissions were under edit field in manage display of the content type.

I had originally looked in both permissions and in edit display.

---
Tags: 7, forms
---


# Question
Title: Print node title in custom block module twig file
I want to send node title and description into twig file. See my code

```
public function build() {

return [
'#theme' => 'block--maincontentlatestnews',
'#latest_news' => $this->read_latest_news(),
'#sample' => 'sample_txt',
'#attributes' => [],
];
}

function read_latest_news(){

$nids = \Drupal::entityQuery('node')->condition('type','article')->execute();
$nodes = entity_load_multiple('node', $nids);

return $nodes ;

}

```

# Answer
> 1 votes
```
return array_map(function($node) {
  return $node->label();
}, $nodes);

```

or if you want links:

```
return array_map(function($node) {
  return $node->toLink()->toString();
}, $nodes);

```

---
Tags: theming, 8, blocks
---


title: How do I remove node URLs?

text:
# Question
Title: How do I remove node URLs?
I have path aliasing, which gets the path from the title of the *News* article, working fine.

However, in the Google index, I noticed that the canonical URL for nodes is working as well. So, Google is indexing the node pages twice: with the canonical URL and with the path alias.

I want to disable the canonical URL for nodes, so I tried installing the node\_page\_disable module. It installed fine, and I enabled it with Drupal 6.

In http://www.example.com/admin/settings/site-information, there is a *Default front page* textbox, which by default contains *node*. If I remove *node* from the textbox, and save the settings, Drupal complains with:

> Default front page field is required.

The module I installed adds a *Retain /node as an active url?* checkbox. If I click on that, I am required to remove *node* from the *Default front page* textbox.

How can I do it, since removing *node* causes Drupal to complain about a required value not given?

# Answer
> 0 votes
Actually I used the Global redirect module to fix this. Here is the guide:

http://www.zyxware.com/articles/3571/solved-drupal-pathauto-google-is-indexing-node-urls-instead-of-url-aliases

Thanks.

# Answer
> 1 votes
You must give a value for *Default front page*, and since you don't want to use *node*, you need to give another value for that setting.

* Enable the Path module that comes with Drupal 6 core, from admin/build/modules

>
* Create a *Page* node, from node/add

>
* Add the path alias you want to use to the node being created

>
* Save it
* Change the default front page, and put the path alias you assigned to the node you just created, on admin/settings/site-information

>
* Save the settings

Now Drupal will use that node as front page.

>

If you installed the *Vertical tabs* module, the node edit page would appear different. In this case, you can find the path alias text-box under the *URL path settings* tab.

>

I used a *Page* node for the front page, but you can use any content type you want.

---
Tags: nodes, 6
---


# Question
Title: Cannot update modules with drush – needs higher bootstrap level
As stated in this answer Drush needs to find the settings.php file in order to work. My problem is that the settings.php file is indeed in the right folder (and I have navigated to the Drupal root folder before issuing the Drush commands), but it still does not work to update modules with drush. I just get the message that `Command pm-update needs a higher bootstrap level to run`. It even states itself that the Drupal settings file is located in `sites/default/settings.php.`

This is the error message:

```
C:\wamp\www>drush ups
Command pm-updatestatus needs a higher bootstrap level to run - you      [error] will need to invoke drush from a more functional Drupal environment
to run this command.
The drush command 'ups' could not be executed.                           [error]

Drush was not able to start (bootstrap) the Drupal database.             [error]

```

I have also followed the instructions in this post, with no luck.

What else can I try?

# Answer
> 1 votes
Finally I found an answer that I could adapt to my WAMP environment here. I simply added `C:\wamp\bin\mysql\mysql5.7.14\bin` to the PATH, and then Drush worked also for updates.

---
Tags: 7, drush
---


# Question
Title: Is there a way to add node grants to anonymous users?
I want anonymous users to be able to access nodes that are promoted to the front page. (They can't access to nodes that are not promoted.) It seems `hook_node_access()` isn't seem called for anonymous users. I tried using `hook_node_grants()` and `hook_node_access_records()`, but the code I am using doesn't seem to give anonymous users access to nodes promoted to front page.

```
function myModule_node_grants(\Drupal\Core\Session\AccountInterface $account, $op) {
   return ['show_promoted_news' => [9999]];
}

function myModule_node_access_records(\Drupal\node\NodeInterface $node) {

  $grants = [];

  if ($node->isPublished() and $node->isPromoted() and $node->getType() == 'article') {
    $grants[] = [
      'realm'        => 'show_promoted_news',
      'gid'          => 9999,
      'grant_view'   => 1,
      'grant_update' => 0,
      'grant_delete' => 0,
      'langcode'     => 'en'
    ];
  }

  return $grants;
}

```

The *access content* permission is overriding the grants I give to the anonymous users, who can't access published content. Adding a greater priority does nothing.

I'm being forced to allow anonymous users to access content and override that when I don't want them to have access with `hook_node_access()`.

# Answer
> 0 votes
You might get this to work by using the Group module. Below are some details about how to do so.

### 1. Configuration

* Create a ***Group Type*** (pick whatever name you want).
* For this case, there is no need for special (custom) ***Group Roles*** for the Group Type you created. Since you'll be able to configure what you want by using these *Special Global Roles* (hardcoded) that come with the Group module (they cannot be defined by the Drupal administrator, and they are always available for any Group Type):

+ "**Outsider**": a signed in user that did not join a group.
    + "**Member**": a signed in user that did join a group.
    + "**Anonymous**": a user that is not signed in.
* Create a ***Group*** (pick whatever name you want) for the Group Type you created, and let's say you name it "Promoted nodes" (feel free to use another name if you prefer).
* Grant the appropriate ***Group Permissions*** for the configured Group Type. To do so, you can also configure for each Content Type which Group Role has what kind of access (= none, view, create, edit, delete). Be aware: even though this looks similar to Drupal's permission configuration, these Group Permissions are not the same permissions (they are specific to the Group module). With the above setup in place, just grant "view" access to the Special Global Role named Anonymous (and pick whatever rights you want for the other roles).

### 2. Granting access

With the above Group module configuration in place, all you need to do is:

* assign each promoted node to the Group "Promoted nodes".
* remove the node from the group again if it is no longer promoted.

For sure this assign/remove can be done manually (whenever a node is edited), but it should be straight forward to somehow automate it using "promoted or not" as the trigger to do so (using the API that comes with the Group module).

### More info

Refer to "How to create collections of content that can be accessed by users with various access levels?" for more info about all this.

---
Tags: 8, nodes, users
---


# Question
Title: Can't render a block due to recoverable fatal error
I had code to programmatically render a block.

```
$block = \Drupal\block\Entity\Block::load('bartik_search');
$block_content = \Drupal::entityManager()
  ->getViewBuilder('block')
  ->view($block);
return array('#markup' => drupal_render($block_content));

```

After updating to Drupal 8.2.x, I get the following error:

> Recoverable fatal error: Argument 1 passed to Drupal\block\BlockViewBuilder::view() must implement interface

How do I fix this error?

# Answer
> 2 votes
The error:

> Recoverable fatal error: Argument 1 passed to `Drupal\block\BlockViewBuilder::view()` must implement interface `Drupal\Core\Entity\EntityInterface`

usually is caused by viewing the invalid block (NULL). So for some reason `Block::load()` fails to load your block (`bartik_search`). So clear your caches and check whether the block exists at *Block Layout* page, theme is enabled and permissions are configured properly. If this still happening and the block is definitely there, please raise a relevant issue ticket.

You can always add the condition or try/catch block whether the code loads the block correctly.

Please also note that ~~`drupal_render()`~~ is deprecated and you should return `$block_content` instead.<sup>@googletorp</sup> Or use `\Drupal::service('renderer')->renderRoot()` instead.

See also: How can I programmatically display a block?

---
Tags: 8, blocks
---


# Question
Title: I'm getting errors from trying to upload images from 2 different fields, server or module issue?
Using Drupal 7 and Siteground hosting, when I try to upload images at registration I get this error, but randomly.

> An unrecoverable error occurred. The uploaded file likely exceeded the maximum file size (128 MB) that this server supports.

The form has 2 image fields, a multiple upload and the standard user image field. Sometimes it works, sometimes doesn't work with both fields.

What could be wrong, hosting issue or module issue?

# Answer
I found my answer:

I had the field set to unlimited images, so it got stuck in a loop, better to set a limit, and then set individual images sizes so they don't exceed the limit.

For example:

1. Field image size limit 10 megs
2. Max images upload 12

So with a limit of 128, 12 images of 10 megs = 120 megs = ok
> 0 votes

# Answer
Most of the time this is hosting issues. Review drupal and php error log to pin point exactly where the issue happens.

Sometimes the upload is successful to the temp folder but it can't move it to the files directory due to permissions ect..
> 1 votes

---
Tags: users, files
---


# Question
Title: Unable to render media from nid:******. Error: No file Id
I'm using node\_embed module to embed nodes into the body of my main content type. This works fine but whenever I save a node with embedded nodes within its body I get the notice `Unable to render media from nid:******. Error: No file Id.` Apparently, this is a generic notice generated by /media/modules/media\_wysiwyg/includes/media\_wysiwyg.filter.inc but it doesn't represent the reality as I'm not really embedding any media.

I've upgraded to the latest version of node\_embed and WYSIWYG and this still happens. From the external documentation of node\_embed:

> Using Node Embed and Media tags:
>
> The WYSIWG integration of Media breaks the Insert Node input filter and removes its content, because the Media tags are using a simular filter tag format as Node embed. To avoid problems you need to process the Insert Node input filter before the Convert Media tags to Markup input filter.

While this is not exactly the issue I'm experiencing, I understand that this issue has to do with the similarity of the WYSIWYG embed formats between node\_embed (\[\[*\]\]) and Media module (\[\[{*}\]\]).

Note: I'm not even using the `Convert Media tags to markup` filter under /admin/config/content/formats/my\_format.

Any ideas on how I can keep my dblog clear from these notices every time I save a node?

# Answer
Adding a negative lookahead in the regex that traces the media embed tags in media\_wysiwyg sub module (media\_wysiwyg/includes/media\_wysiwyg.filter.inc) seems to do the job.

From the patch submitted on drupal.org for this issue:

```
diff --git a/modules/media_wysiwyg/includes/media_wysiwyg.filter.inc b/modules/media_wysiwyg/includes/media_wysiwyg.filter.inc
index a284752..c9c6130 100644
--- a/modules/media_wysiwyg/includes/media_wysiwyg.filter.inc
+++ b/modules/media_wysiwyg/includes/media_wysiwyg.filter.inc
@@ -455,7 +455,7 @@ function _media_wysiwyg_generate_tagMap($text) {
// between function calls. Since media_process_form is multiple times
// with same form, this function is also called multiple times.
static $tagmap = array();
-  preg_match_all("/\[\[.*?\]\]/s", $text, $matches, PREG_SET_ORDER);
+  preg_match_all("/\[\[(?!nid:).*?\]\]/s", $text, $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
// We see if tagContent is already in $tagMap, if not we add it
// to $tagmap.  If we return an empty array, we break embeddings of the same

```
> 0 votes

---
Tags: nodes, wysiwyg, debugging, media
---


# Question
Title: In drupal 7, what does make a menu link a stale item?
I'm creating menu links with this kind of code:

```
$item = array(
  'link_path' => drupal_get_normal_path('link-path'),
  'link_title' => 'link-title',
  'menu_name' => 'menu-name',
  'weight' => 0,
  'expanded' => 1,
);

// Look the table first if the data does exist
$menuId = db_query("SELECT mlid from {menu_links} WHERE link_title=:link_title AND link_path=:link_path", array(':link_title' =>
$link['link_title'], ':link_path' => $link['link_path']))->fetchField();
if ($menuId === FALSE) {
    $menuId = menu_link_save($item);
    echo "New entry " . $menuId . PHP_EOL;
} else {
    echo "exists " . $menuId . PHP_EOL;
}

```

Later on, if I call any of these functions:

* `menu_rebuild()`
* `drupal_flush_all_caches()`
* Or if I clear the cache from the web ui.

All my menu links are deleted. According to the documentation, these functions "remove stale items from {menu\_links}". And I am unable to find out what is missing in the parameters of `menu_link_save` or if I need an extra step. If I stop the script before flushing, the content table menu\_link looks OK.

I'd like some explanations about the workflow of `menu_rebuild` that causes some objects to be deleted (i.e. is there a flag or something, etc.).

# Answer
Is it related to Stale menu link static caches? https://www.drupal.org/node/2425261
> 0 votes

---
Tags: caching, navigation
---


# Question
Title: How to print fields value in views-view.html.twig in drupal 8
How to print fields value in views-view.html.twig I have created a `views-view.html.twig` file for my view `slider_3`. The template name is 'views-view--slider\_3.html.twig' The view formatting is done by this template, but I need a field is come at begging position of the view:

`<div class="slider-3-main">{{ rows.required_field }}
<div{{ attributes.addClass(classes) }}>
 {{ title_prefix }}
 {% if title %}
 {{ title }}
 {% endif %}
 {{ title_suffix }}`

How can be the field will written to display at `{{ rows.required_field }}`

# Answer
> 2 votes
To get a field value of the first result row `view.result[0]` use the method EntityField::getValue of the view field:

```
{{ view.field.field_example.getvalue(view.result[0]) }}

```

---
Tags: views, theming
---


# Question
Title: How to use the Message module to log site and user activity?
I am just unable to use the Message module or the Activity module to record the following activities and show them in a view.

1. User A just got 10 points.
2. User B just became User A's friend.
3. User C just joined the site.
4. User D just logged in.
5. User E just viewed "Any Blog".
6. User F just commented on "Any Blog".

The Activity module does not provide hooks for some of this in the CMS UI itself and I am having real difficulties to configure the Message module for these cases.

There is not enough documentation for this, especially the Message module. There is one tutorial at Log Site Activity with Message and Rules but that is for only one of my cases. I haven't been able to figure out the other use cases. I don't get exactly the same options (entity and tokens) as described in the tutorial.

Any help with my use cases?

# Answer
The Message module is great, really! But still poorly documented. However, have a look at the tutorial "How to use Rules to notify users about new or updated posts on a Drupal site?", which explains how to use the Message module, together with the Rules module. What follows is a summary of what's included in this tutorial.

> You can use the Message module in combination with the Rules module create message "entities" (which is what you get if you use the Message module). And then just use the power of Views to display those messages that got created in the format you need (page, block, etc).
>
> Here is a blueprint of what you'd need:
>
> 1. Define an appropriate Message type, using the Message module. Think of Message types as similar to "Content types", which will be used to create Messages, similar to nodes.
> 2. Create a rule with a Rules Action "Create entity" (of type "Message"). Refer to the answer in '*Which user related token(s) can be used to create a Rule for setting up a message type?*' for some examples.
> 3. Make sure to also add a Rules Action to pass any relevant tokens, via the Rules module, as *Replacement tokens* that you can use in your Message type you created with the Message module. Refer to What's the purpose of "Replacement tokens" of a Message type? for more details on this.
> 4. Use Views to display the created messages in the format you prefer.

Some more details specific to your question here:

* For each of the 6 activities you want to record, define an appropriate (corresponding) Message Type (using the Message module). Let's name those message types like M1, M2, ... M6 for now.
* For each of the 6 activities you want to record, there is an appropriate Rules Event you can take advantage of. If you'd just create 6 custom rules (1 for each activity to record, let's name those rules like R1, R2, ... R6 for now), it's a matter of combining each rule with a Rules Action to "Create an entity" (i.e. of type "Message"). E.g. Rule R3 should have a Rules Action to create a message of type M3.
* As per the "*I don't get exactly the same options (entity and tokens) ...*"-part of your question: I bet sooner or later you're going to run into the issue that you want to create a message using a token which is NOT made available by only the Message module. E.g.: Assume that for recording your 6th activity (= "*User F just commented on ...*") you want the message to also include the actual comment body (text) that was posted. But the Message module doesn't offer any relevant token related to that comment body. In that case, you can use the approach/solution as documented in "What's the purpose of "Replacement tokens" of a Message type?", which is basically a technique to create your custom tokens (the comment body in the example here) and make them available to the Message module (so that you can include them in the message to be created).
* Obviously, creating appropriate views of these messages (which are just entities) should be straight forward.

### More info about the Message module

There is *not a lot of documentation* available about the Message module, which is what makes it a hidden Drupal gem. A possible way to get started with it, and to get an idea of the kind of things it can be used for, is to also have a look at these tutorials:
> 0 votes

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


# Question
Title: How to use jQuery tabs to show three tabs of three different views?
I have three separate Content Types, with three table Views for each, and they are being displayed in three separate pages. But now I want to use jQuery UI Tabs to have just one page with three tabs. How do I do this? Do I need to change the View to display a Block instead of a page and go from there? Where in Drupal do I install jQuery Tabs at?

# Answer
You can try with Quick Tabs module.

> The Quick Tabs module allows you to create blocks of tabbed content, specifically views, blocks, nodes\* and other quicktabs\*. You can create a block on your site containing multiple tabs with corresponding content. Clicking on the tabs makes the corresponding content display instantly, using jQuery.

I used it before and it's working great.
> 0 votes

---
Tags: views, javascript
---


title: How to encrypt drush backups with gnupg

text:
# Question
Title: How to encrypt drush backups with gnupg
I am trying to set up a cron job that automatically backups up a Drupal site using drush but then encrypts that file. I would like to accomplish this using a single command but am not sure how to go about it.

Here is the command that does the backup and logs any messages (this works):

```
drush @mysite archive-dump --destination="/home/drush-backups/archive-dump/mysite.$(date +\%F_\%H-\%M-\%S).tar.gz" &>> /var/log/mysites/$(hostname -s)/drush-cron.log

```

However when I try this:

```
drush @mysite archive-dump --destination="/home/drush-backups/archive-dump/mysite.$(date +\%F_\%H-\%M-\%S).tar.gz" | gpg -e -r mypublickey &>> /var/log/mysites/$(hostname -s)/drush-cron.log

```

It does not work. Any ideas where I am going wrong? What is the correct command?

Thanks.

# Answer
> 1 votes
You're piping the output of the Drush command to `gpg`, but it's expecting a file path.

By default the output will not be something that `gpg` can use, but `archive-dump` has a handy `--pipe` option which will print just the path to the output file; `gpg` can use that:

```
drush @mysite archive-dump --pipe --destination="/home/drush-backups/archive-dump/mysite.$(date +\%F_\%H-\%M-\%S).tar.gz" | gpg -e -r mypublickey &>> /var/log/mysites/$(hostname -s)/drush-cron.log

```

---
Tags: drush, cron
---


title: Rendering blocks inside node

text:
# Question
Title: Rendering blocks inside node
I am building a Drupal 8 site. The site will have basic pages (nodes) that have three fields: a title, a body and a list of embedded blocks. The idea is to allow the editors to create content blocks by using the new functionality of Block Types in Drupal 8. Those blocks can be referenced and arrangaed inside the page by using an entity reference field.

I have built the necessary infrastructure and I can reference my custom blocks from the page and render them in the template. The trouble comes when I want to set a custom template for my blocks, for example I would like to have a custom template: *block--image-gallery-block.html.twig* that would be used when rendering blocks of type Image Gallery Block.

With Twig debug mode enabled I can see that Drupal is looking for a template for the entity reference field, and then starts to render the referenced block fields instead of the block itself, so I can not use any template for it (not even the default *block.html.twig*).

I've thought about using a custom template for my field and render here the block the way I like. Unfortunately my field can reference blocks of multiple types, so this solution won't work for me.

How can I make Drupal pick the proper template for the referenced blocks?

**Edit: solution**

I am explaining here the solution I've ended with after reading @ssibal and @4k4 answers.

1. I've built some new content-types that will represent the blocks.
2. I've modified my *Basic Page* content type to have an *entity reference* field that points to the blocks. This field simply references other nodes from the content types that I want (the ones I've made in the step 1).
3. In the *display options* of my basic page, I choose which view mode I want to use for rendering the blocks.
4. I use the view mode that I've set up in the step 3 to build custom templates for my block content types.
5. Since I do not want block content types to be accessed directly with a URL, I've implemented a hook\_node\_access to throw a 404 error when directly loading a node of my block content types.

# Answer
> 2 votes
> Those blocks can be referenced and arrangaed inside the page by using an entity reference field.

These "block contents" should be a different content type, since you are not using (based on your writing) the block functionality at all. After that, you can define your own display for this content type, and also create a twig template for it.

# Answer
> 0 votes
**Block content** is not the same as **Block**.

**Block content** is a content entity

**Block** is a config entity.

Normally you place "block content" in a "block" to put it on your drupal site. Then you get a block template around your block content.

You are using "block content" as entity in a reference field, then this is no "block" and will not involve the block theme.

But you should be able to do the same theming in the field template of the reference field.

You can go inside the items loop and check every item, which kind of block content is inside and make your adjustments.

# Answer
> 0 votes
You can use Block Token to expose blocks as tokens, then use Token Filter to use these tokens on the node pages, so they can render the blocks. See: How to use tokens in a node?

---
Tags: theming, nodes, 8, blocks
---


# Question
Title: drush 8.1.9 on php 7 not giving any "drush status" in docroot folder
I just setup a fresh install of drupal 7, ubuntu 16.04, installed php 7.0 and git cloned the drush repo which checkout of 8.1.9 drush. When I do a drush status on the docroot of my drupal folder it shows the following and when doing a drush dl it fetches only drupal 8 modules.

```
 PHP executable         :  /usr/bin/php
 PHP configuration      :  /etc/php/7.0/cli/php.ini
 PHP OS                 :  Linux
 Drush script           :  /vendor/drush/drush/drush.php
 Drush version          :  8.1.12
 Drush temp directory   :  /tmp
 Drush configuration    :
 Drush alias files      :  /home/ubuntu/.drush/hotsite.aliases.drushrc.php

```

When I used to run php 5.6, it would give me all the details of my install. What did I do wrong here?

---- updated with drush status in the sites/default folder:

```
$:/var/www/hotsite_d7/docroot/sites/default$ drush status
 PHP executable         :  /usr/bin/php
 PHP configuration      :  /etc/php/7.0/cli/php.ini
 PHP OS                 :  Linux
 Drush script           :  /vendor/drush/drush/drush.php
 Drush version          :  8.1.12
 Drush temp directory   :  /tmp
 Drush configuration    :
 Drush alias files      :  /home/ubuntu/.drush/aliases.drushrc.php

$/var/www/hotsite_d7/docroot/sites/default$ drush @hotsite status
 Drupal version                  :  7.57-dev
 Site URI                        :  http://default
 Database driver                 :  mysql
 Database hostname               :  127.0.0.1
 Database port                   :
 Database username               :  xxx
 Database name                   :  xxx
 Database                        :  Connected
 Drupal bootstrap                :  Successful
 Drupal user                     :
 Default theme                   :  bootstrap
 Administration theme            :  seven
 PHP executable                  :  /usr/bin/php
 PHP configuration               :  /etc/php/7.0/cli/php.ini
 PHP OS                          :  Linux
 Drush script                    :  /vendor/drush/drush/drush.php
 Drush version                   :  8.1.12
 Drush temp directory            :  /tmp
 Drush configuration             :
 Drush alias files               :  /home/ubuntu/.drush/aliases.drushrc.php
 Install profile                 :  standard
 Drupal root                     :  /var/www/hotsite_d7/docroot
 Drupal Settings File            :  sites/default/settings.php
 Site path                       :  sites/default
 File directory path             :
 Temporary file directory path   :  /tmp

$/var/www/hotsite_d7/docroot/sites/default$

```

# Answer
Drush usually does this when it cannot find a Drupal installation, which happens when it cannot find a `settings.php`. Did you go through the installation process yet? (visiting `install.php` on the browser or doing `drush site-install`)
> 1 votes

---
Tags: 7, drush
---


# Question
Title: How can I copy the html from one node to another programmatically?
I have an angular app running in a drupal page. The app goes out and fetches item data from an API, and displays the formatted item data in the drupal page.

I have no way of searching the data returned by the angular app -- as far as drupal is concerned, the page is blank.

Is there a way to copy the html created by the angular app, from the page where it resides, to another page as raw html? That should make it visible to drupal.

# Answer
> Is there a way to copy the html created by the angular app, from the page where it resides, to another page as raw html? That should make it visible to drupal.

You're approaching the problem from the wrong angle. The root of the problem is that Drupal does not have the data supplied by the API, and NOT because Drupal does not have the HTML from Angular. Consider syncing Drupal with your API endpoint instead.

One route is to use the Feeds module, together with Feeds Tamper for pre-processing and Feeds Ex to allow various data formats. Another approach is to use the Migrate module.
> 1 votes

---
Tags: nodes, javascript
---


# Question
Title: Theming/Aligning Multiple Views Blocks on Homepage
I have an **article** content type which has a category field that is an **entity reference** field type linked to a **taxonomy** group of terms I created.

The website has 6 different **pages** which are just a taxonomy view based on the 6 different article categories listing the articles that are associated with that category. These are the settings of the taxonomy view used for each of the pages:

What I'm trying to do is create 6 **block views** on the homepage in a grid where each block view is a different category title showing the 4 most recent article titles and a *more* button to take you to the listing page of said category view. Each background would be a different image based on my CSS. This is what I'd like it to look like:

I'm using Boostrap so what I'd like is each row to be put within a `<div class="row">` and then each block to have a `<div class="col-sm-4">`.

What I want the final code for each block to look like is the following:

```
<div class="col-md-4">
  <div class="category background-img-class-name">
    <div class="category__content">
      <div class="category__content--title">
        <h3>{{ category.title }}</h3>
      </div>
      <ul class="category__content--listings">
        <li><a href="{{ link.to.article.1 }}">Article Title 1</a></li>
        <li><a href="{{ link.to.article.1 }}">Article Title 2</a></li>
        <li><a href="{{ link.to.article.3 }}">Article Title 3</a></li>
        <li><a href="{{ link.to.article.4 }}">Article Title 4</a></li>
      </ul>
      <div class="category__content--more">
        <a class="btn btn-primary" href="{{ link.to.category.view }}">More</a>
      </div>
    </div>
  </div>
</div>

```

I know I could create a different block view in views for each of these (would that be the best practice?) and then place them in the content region only on the homepage but then how would I theme the template files so that I could have them work the way I've shown above?

Is there a better approach to this than what I'm suggesting above? Any help/suggestions is greatly appreciated. Also, if something **exactly** like this has been asked/answered before, a link to that would be helpful as I've tried searching on here and haven' been able to find anything exactly like my issue.

# Answer
> 0 votes
Please comment below if I have misunderstood anything and I can modify my answer.

First, I will clarify that I understand what is happening.

To the user, there appear to be 6 different pages on the site but in actuality, they are looking at the View Page that you posted above with contextual filters (each containing a different taxonomy term).

On the homepage, in a grid, you would like to display 6 Block Views that display the 4 most recent posts for their respective Taxonomy Term.

You would want Views to print out in a Bootstrap-like format so that they utilize the Bootstrap responsive grid.

---

This is what I recommend:

* First we are going to create the first New Block.
* Create a Block View called "Front Page News Blocks" (Or something along those lines) that lists Nodes of the Article type
* Limit the View to only display 4 nodes
* Ensure that it is sorted via post date (Ascending)
* Add a "Custom text" field to the view and put the "More" link (with the btn and btn-primary classes) in the value
* All of the above settings are "Applied to All Displays"
* Now, you want to create some Block Views within this View. Have a total of 6 different Block Views
* Within these, you can add categories Filters (but apply them only to the respective displays)
* Also, override the URL in the "More" link in each view (Once again, don't forget to only apply it to the current display)
* Create a template based on views-view.html.twig but name it after your View to override the default theme file
* Within your custom TWIG file, you can add the "col-md-4" grid classes
* You would also need to override the Homepage template so that you can add a div with the "row" class to the region where these blocks will be.
* Now your CSS classes should be in the markup and you should be able to style your site as planned.

What I laid out was pretty generalized and high level. Definitely comment below if you need clarification on anything and I can edit this answer.

Hope this helps get you on the right track!

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