title: How to add blog preview to home page?

text:
# Question
Title: How to add blog preview to home page?
I've got a blog set up on my site, with a separate page holding all the blog posts. I've created a custom content type for making the individual blog posts so when a new post is created a preview is displayed in a list under a 'view', like any normal blog.

I would like to know how can I also list the blog previews (or teasers) on the home page as well as the main blog page?

# Answer
*I would like to know how can I also list the blog previews (or teasers) on the home page*

You can do this using views in both D7 & D8. If you go at Structures/Views, you will find the view name `Front page`, you can enable that view which by default works as front page in Drupal. So as per you need, you just need to apply filter for `blog` content type and in view mode you can set it as `teasers`.

*as well as the main blog page?*

Same way you can make new view and give new path/url to that view and set it as `main blog page`.

**Illustrations of above details:**

**1. Default front page view at Structures/views**

>

**2. Front page view setting page:** I have changes the filter parameters so it will show only blog posts at home-page.

>

**3. Output image:** HOME page showing only blog previews.

>
> 1 votes

---
Tags: 7, views, nodes
---


# Question
Title: entity reference as attribute, is it possible in commerce v2?
User story: The end-users should be able to pick an image from an image gallery and attach that image to a product before adding it to cart

In Commerce v1 this was possible via line items by defining an entity reference field, along with a couple of other modules e.g. entityreference view widget. A sample, although not 100% finished, can be found in d7demo when you click on the 'add item' button.

I used entity reference since the images are actually nodes with a file field, so that i could also categorise them via term references.

Is the above functionality somehow possible on commerce v2? I cannot find 'line items' as used in v1, but only attributes and variants. However i cannot seem to find the way (configuration or contribs) to achieve the above functionality.

Any pointers to the above issue are very much appreciated.

# Answer
Since product attributes are entities in CommerceV2, the following module should cover your needs =\> https://www.drupal.org/project/entity\_browser

Some points to consider:

* It is still in alpha
* It is strongly supported at the moment by the community and especially the Drupal Media Team
* It has more than 5K downloads.

There is also a recent presentation available from DrupalCon Dublin 2016 =\> https://www.youtube.com/watch?v=VXor-HZiYrs

Update: Following the documentation, you may also need to look into "Product Variations Fields", http://docs.drupalcommerce.org/v2/product/products.html.
This CV2 functionality seems to allow you to expose specific fields to the end-user for e.g. uploading images in order to modify/configure a product.

Good luck!
> 1 votes

---
Tags: 8, commerce
---


# Question
Title: What does INTERNAL form properties mean?
On the Drupal form-API page, there is this paragraph that reads:

> Note that internal properties are not included in the table below, but are included in the Properties list. These include: #built, #children, #error, #id, #input, #printed, #validation\_arguments

What does "internal" mean, as compared to other form element property types?

# Answer
> 0 votes
**Internal** means that these properties are not supposed to be used by module developer.

---
Tags: theming, forms
---


title: Theming login page--user--login.tpl.php

text:
# Question
Title: Theming login page--user--login.tpl.php
I'm trying to theme the login user page and it seems that I'm missing something and I can't figure out what it is.

here is what I did:

I've added this code to my template.php:

```
 function mxblog_theme() {
  $items = array();
  // create custom user-login.tpl.php
  $items['user_login'] = array(
  'render element' => 'form',
  'path' => drupal_get_path('theme', 'mxblog') . '/templates',
  'template' => 'page--user--login',
  'preprocess functions' => array(
  'mxblog_preprocess_user_login'
  ),
 );
return $items;
}

```

and this that I'm trying to render in the page--user--login.tpl.php

```
   print drupal_render($form['name']);
    print drupal_render($form['pass']);

```

```
    print drupal_render($form['form_build_id']);
    print drupal_render($form['form_id']);
    print drupal_render($form['actions']);
```

# Answer
When using page--user--login.tpl.php you have to manually fetch the user login form, as your overriding the entire page template not just the form.

You can either include this directly in the template (along with any other markup):

```
print drupal_render(drupal_get_form('user_login'));

```

Or in your mxblog\_preprocess\_user\_login() function must return the form:

```
function mxblog_preprocess_user_login(&$variables){
  $variables['form'] = drupal_get_form('user_login');
}

```

then in the template you should be able to to do as you want:

```
print drupal_render($form['name']);
print drupal_render($form['pass']);
print drupal_render($form['form_build_id']);
print drupal_render($form['form_id']);
print drupal_render($form['actions']);

```
> 1 votes

# Answer
Thanks for your answers :) For those who are interested, here is what I did:

I created a user-login.tpl.php (note the single '-') and then I added a background image:

.page-user-login { position: fixed; left: 0; top: 0; width: 100%; height: 100%;

background: url('xxx/login\_BG\_rezised.jpg') no-repeat center center fixed; background-size: cover;

}

LES PROS DU BTP ONT LA PAROLE Votre média pour s'informer et communiquer.
```
<div class="login-page">

```

```
<form class="login-form">

<span class = "login-form-info"> Inscription rapide et GRATUITE. </span>
 <input type="text" placeholder="Nom utilisateur" name="name" id="edit-name" required="required" class="form-text required"/>
 <input type="password" placeholder="Mot de passe" name="pass" id="edit-pass" required="required" class="form-text required" />

<input type="hidden" name="form_id" id="edit-user-login" value="user_login"  />
<input type="submit" name="op" id="edit-submit" value="Connectez-vous" class="form-submit" />

<p class="message">Pas de compte? <a target="_blank" href="https://xxx/user/register">Créez votre compte</a></p>
<p class="message">Mot de passe oublié? <a target="_blank" href="https://xxx/user/password">Renvoyez le moi</a></p>

```

added some css style for the form to look the way I wanted.
> 0 votes

---
Tags: 7, users, authentication-authorization
---


title: PHP code in a block

text:
# Question
Title: PHP code in a block
I have a block with HTML and CSS design, now I need to add 3 different dynamic data (which are in different tables) using PHP in 3 different part of the block, I would like to know how can I do that ?

Should I create a module ? And if yes, how can I show data from the module in to the block ?

Or is there any other way to do that ?

\*We are using Drupal 7 !

*I already tried costume block which I found by my searches, but it's not working ! Or at least, I don't know how to use it !*

\*I'm also looking for more secure solution !

# Answer
You mean a block like in admin/structure/block/add? When adding a block, the text configuration should be set to PHP. It's not on by default.

* Enable module PHP filter (core) in Look in /admin/modules.
* Go to /admin/config/content/formats and add a new format.
* Select under 'enabled filters' PHP-evaluator.
* When making a new block, choose the new text format.
* Usually, only user/1 (admin) needs this, but you can add roles with access to the PHP-format.
> 1 votes

---
Tags: 7
---


# Question
Title: Adding taxonomy term list to another taxonomy term's overview
Let me start by saying I'm fairly new to Drupal. I'm using Drupal 7.

I have a content type "product" which is assigned to one or more taxonomy terms in "collections" (taxonomy). Then I have another taxonomy called "brands".

The "brands" taxonomy has a field reference to a "collections" taxonomy term. For instance: brand "Google" can be assigned to collections "Shoes" or "Bags".

On the collection page for "Shoes", all the products tagged "Shoes" are being displayed. On top of the page, I want to add a list of all the brands in the "brands" taxonomy, that are assigned to this particular collection ("Shoes"). They are independent from the products themselves. How would I display this list on top of the page? Do I need to create a custom overview?

# Answer
In this case you need to a create view that displays block on top of the collection page.
The view should display taxonomy terms in the "collections" vocabulary filtered by a contextual filter (taxonomy term id) so that only the desired taxonomy term is display.
Next you should add a relationship using the field reference you're using on that term.
Finally you can use the relationship to display fields or taxonomy terms to the display.

I tried to explain it briefly, let me know if you need further explanation.
> 1 votes

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


# Question
Title: How do I migrate the content of a SQL table?
I have a sql table which contains Visitor name, Afiliation, Start date and End date.

I have created a content type named "Visitors" which contains title (i.e Visitor name), Affiliation (Text field), Start and end date (Date field)

How can I migrate my sql records from tables to populate this content. Please share the online resource link and other material which can help me to achieve this objective.

I am using Drupal 7.

Thank you for your help

# Answer
You can achieve it using the Feeds module.

> * Import or aggregate data as nodes, users, taxonomy terms or simple database records.
> * Import or aggregate CSV files
> * Create nodes, users, taxonomy terms or simple database records from import
> * Extensible to import any other kind of content
> * Granular mapping of input elements to Drupal content elements
> * Exportable configurations
> * Batched import for large files

### Reference
> 1 votes

---
Tags: 7, migrations
---


# Question
Title: "Place block" ajax error when using nginx
I'm having a lot of trouble configuring nginx properly for Drupal 8. Using the Drupal nginx recipe on the official site works well except for opening modal dialogs like the "Place block" dialog. This results in a 200OK response but an ajax error.

Here is a gist with the error.

I know this is an nginx configuration issue as I have a different conf file that doesn't cause this issue. This other configuration doesn't work with Drupal 8's active link javascript due to the way it adds the query parameters. Frustrating!

# Answer
> 0 votes
Sometimes writing it down helps to figure things out! The missing bit of configuration needed is `fastcgi_param QUERY_STRING $query_string;`

With the Drupal nginx recipe but with that line added in the `location ~ '\.php$|^/update.php' {` block its now working as expected, both the `is-active` class is added to the active menu link and the "Place block" ajax works properly.

---
Tags: ajax, 8
---


# Question
Title: How to update the version of AngularJS using module configuration
I'm trying to build an application using Drupal and AngualarJS. When I download and enable the drupal-angualar module(https://www.drupal.org/project/angularjs) it shows the top version as 1.3.4, but I want to use the latest angular version(1.5.8).

How can I update the angualar version to latest?

# Answer
As @Jimmy Ko suggested I have fixed the issue as follows:

I have added the following code in the function `angularjs_version_files()` of file `sites\all\modules\angularjs\angularjs.module`. Then selected the AngularJS version 1.5.8 in `admin/config/development/angularjs`.

```
$files['1.5.8'] = array(
    'angular-animate',
    'angular-aria',
    'angular-cookies',
    'angular-loader',
    'angular-messages',
    'angular-mocks',
    'angular-resource',
    'angular-route',
    'angular-sanitize',
    'angular-scenario',
    'angular-touch'
  );

```

Now, in the view source I can see the latest AngularJS file is included in my project.
> 1 votes

---
Tags: 7
---


# Question
Title: Bulk registration or disallow registering of certain usernames
I need to register 1000+ usernames at once. How to do it?

Or is there any way to disallow from registering 1000+ usernames? People could not register certain usernames.

I need to reserve these usernames for payed registration.

# Answer
You can do this by code, alter the registration form (***hook\_form\_user\_register\_form\_alter***), in a custom module like:

```
function MY_MODULE_form_user_register_form_alter(&$form, &$form_state, $form_id) {
    $form['validate'][] = 'reserved_usernames';
}

```

And then implement the validation (in the same MY\_MODULE.module file) method like:

```
function reserved_usernames ($form, &$form_state) {
  $reserved = array();
  $reserved[] = 'reserved_name';
  $reserved[] = 'reserved_name_1';
  $reserved[] = 'reserved_name_2';
  $reserved[] = 'reserved_name_3';
  $reserved[] = 'reserved_name_4';
  $reserved[] = 'reserved_name_5';

  if (in_array($form_state['values']['name'], $reserved)) {
    form_set_error('name', t('The name %name cannot be taken.', array('%name' => $form_state['values']['name'])));
  }
}

```
> 2 votes

---
Tags: 7, users
---


# Question
Title: Override core permissions used for visualizing a page
Is there is a way (without using any external module) to override the core drupal 7 pages access permissions , for example and by default you will not be able to access **/admin/structure/taxonomy/tags** page without having (**Administer vocabularies and terms)** permission , but I want the users to be able to access it if they have for example **(Edit terms in Tags)** permission

# Answer
You can make it by writing a custom module that implements `hook_menu_alter()`.

```
function mymodule_menu_alter(&$items) {
  $items['path/to/change']['access arguments'] = array('permission name');
}

```
> 3 votes

---
Tags: 7, users
---


# Question
Title: Views grouping rows case-sensitive, I need to ignore case
I have a view which groups rows in a table according to the first letter of the title. Some of the letters are uppercase and some are lowercase. View treats the upper and lower case as separate groupings (see image attached) but I want them to be grouped case-insensitively.

I've checked my db tables are ci and I've tried to alter the query using `hook_views_query_alter` but haven't managed to find a solution yet.

Thanks

# Answer
> 3 votes
The query executed is corrected, when adding a count value on the grouping (for example when adding a glossary), you will get a count with merged grouping (case-insensitive).

The problem here is when adding a `Grouping field` with `Use rendered output to group rows` enabled, it will do the grouping with case-sensitive because a `B` is not equal to `b`. To resolve the problem, you can implement `YOURMODULE_views_pre_render()`, and clone the institution name to a new datamember and transform this to uppercase. To notify the view that the grouping field should use the new created datamember, you can change its alias.

Here is some sample code

```
function YOURMODULE_views_pre_render(&$view)
{
    // only execute code on 'your_view_name'
    if ($view->name !== 'your_view_name') {
        return;
    }

    // 'title_grouping' is the field used to regroup the nodes
    // 'node_title_upper' is the new datamember that will be added to node object
    $view->field['title_grouping']->field_alias = 'node_title_upper';

    // loop through each node, and assign an uppercased node title to the 'node_title_upper' datamember
    foreach ($view->result as $result) {
        $result->node_title_upper = strtoupper($result->node_title);
    }
}

```

# Answer
> 3 votes
In Drupal 8, this can be done pretty effortless thanks to Twig. Just override the output of the grouping field with its value plus Twig's built-in uppercase filter (`|upper` or `|capitalize`), see screenshot:

# Answer
> -1 votes
Quick and easier way.

If you are using views PHP field, Then convert required field to uppercase using strtoupper() function right there.

Then group views result by this converted PHP field.

---
Tags: views
---


# Question
Title: How to load the node to print the node title, etc?
I have a content type 'news' and created a seperate template for this which is `node--news.html.twig`. I want to load the node like Drupal 7 so I can print the node title, body and other fields as well. In Drupal 7 we load the node by `node_load($nid)` but is there any way to load the node in Drupal 8?

# Answer
When you are in a node template like `node--news.html.twig`, then the node is already loaded in the variable `node` and you can access the field values in twig:

```
{{ node.field_myfield.value }}

```

You get the raw values from the database. They are escaped by twig, to prevent hacks. But this escaping makes them useless for any html formatted content.

Most times you use the field values from node for logic, like checking a boolean.

If you want to display the fields, it is preferable to use `content`:

```
{{ content.field_myfield }}

```

The node title is preloaded in the variable `label`:

```
{{ label }}

```
> 3 votes

# Answer
Load the node using either `\Drupal\node\Entity\Node::load()` (whose first argument is the node ID) or `\Drupal\node\Entity\Node::loadMultiple()` (whose first argument is an array of node IDs, and which returns multiple nodes).

Once you have a node object in `$node`, you obtain its title from `$node->getTitle()`.
> 13 votes

# Answer
One way is to get the title and body of your content type by using views. Create a 'news' view of content type news and select fields - title and body.

Now in your current theme's template folder, create a file :

```
views-view-table--news--block.html.twig

```

There you can fetch title and body field and style as you want:

```
{% set i = 1 %}

 <div id="tabs">
    <ul>
      {% for key,row in rows %}

        <li><a href="#tab-{{key+1}}">

         {% for column in row %}

         {{ column.field_display_date_1 }} </a></li>

        {% endfor %}

      {% endfor %}
    </ul>

```

Also you can use below query in your custom module if you don't want to use views module. It will load node object of content type 'news':

```
$nids = \Drupal::entityQuery('node')
         ->condition('type', $content_type, '=')
         ->condition('langcode', $language, '=')
         ->condition('status', 1, '=')
         ->execute();

  $nodes = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($nids);

foreach ($nodes as $key => $value) {
  $title =  $value->title->value;
  $description =  strip_tags($value->body->value);
}

```
> 3 votes

---
Tags: 8
---


# Question
Title: Adminimal template and CCS adjustments and priority of css files?
In Drupal 7 i use the adminimal template for some pages.

I want to adjust some element and added therefore a SASV file into the theme. Now some elements I can override but some elements (like table th) are not going well. Looking into a deeper way I can see the priority of the files:

1 custom.css (with my adjustments) 2 reset.css 3 style.css

So Style.css is applied as last. But style css is not in the info file?!?!

In the adminimal.info file I added:

```
; ========================================
; Stylesheets
; ========================================
stylesheets[all][] = css/custom.css

```

How to change the order of this processing ?

# Answer
> 0 votes
Solved by

```
 drupal_add_css($adminimal_path . '/css/custom.css', array('group' => CSS_THEME, 'media' => 'all', 'weight' => 2));

```

in the template.php file

---
Tags: 7, theming
---


title: HTML showing as text

text:
# Question
Title: HTML showing as text
i am using below code to show content in admincontroller of my module but $filelink is show as text instead of html

i tried to show href link in $filelink but it renders and text content like below:

```
<a href='abc/pdf_2.pdf' target='_blank'>Resume</a>

```

but i want it as

Resume

```
  function content() {
    $url = Url::fromRoute('bd_career_add');
    //$add_link = ;
    $add_link = '<p>' . \Drupal::l(t('New Submission'), $url) . '</p>';

    $text = array(
      '#type' => 'markup',
      '#markup' => $add_link,
    );

    // Table header.
    $header = array(
      'id' => t('Id'),
      'name' => t('Name'),
      'number' => t('Number'),
      'email' => t('Email'),
      'email' => t('Resume'),
      'operations' => t('Delete'),
    );
    $rows = array();
    foreach (BdCareerStorage::getAll() as $id => $content) {
      // Row with attributes on the row and some of its cells.
      $editUrl = Url::fromRoute('bd_career_edit', array('id' => $id));
      $deleteUrl = Url::fromRoute('bd_career_delete', array('id' => $id));

    $file = \Drupal\file\Entity\File::load($content->resumefid);
    $filelink ="<a href='".file_create_url($file->getFileUri())."' target='_blank'>Resume</a>";

      $rows[] = array(
        'data' => array(
          \Drupal::l($id, $editUrl),
          $content->name.' '.$content->lname,$content->number,$filelink,
          \Drupal::l('Delete', $deleteUrl)
        ),
      );
    }
    $table = array(
      '#type' => 'table',
      '#header' => $header,
      '#rows' => $rows,
      '#attributes' => array(
        'id' => 'bd-career-table',
      ),
    );
    //return $add_link . ($table);
    return array(
      $text,
      $table,
    );
  }

```

# Answer
> 0 votes
solved it using below code:

```
$file = \Drupal\file\Entity\File::load($content->resumefid);
$filelink = file_create_url($file->getFileUri());

$url = Url::fromUri($filelink);
$external_link = \Drupal::l(t('Download Resume'), $url);

  $rows[] = array(
    'data' => array(
      \Drupal::l($id, $editUrl),
      $content->name.' '.$content->lname,$content->number,$external_link,
      \Drupal::l('Delete', $deleteUrl)
    ),

```

---
Tags: 8
---


# Question
Title: How DO I store/retrieve data and display them in templates?
Coming from THE MVC pattern of Django, I am unable to grasp the concept in Drupal 8. I know Twig is used for templating, but what about storing/retrieving data in Drupal 8 and displaying them in templates? Suppose I have a content type (*Activity*) with fields like *Image*, *Body*, *Files*, etc. Someone can create multiple activities with a WYSIWYG editor. How do I retrieve all these nodes and display them in a page applying my own styles (not using views). Django Views are suitable for this. Can I do this without developing a module?

# Answer
One way to achieve this is using preprocess function. In your theme's '.theme' file, write a preprocess function. Example: In `bartik.theme`

```
function bartik_preprocess_html__node__28(&$vars) {

$nids = \Drupal::entityQuery('node')
        ->condition('type','article','=')
        ->condition('status',1,'=')
        -> execute();
$nodes = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($nids);
foreach ($nodes as $key => $value) {
$title = $value->title->value;

}
$vars['title'] = $title;

}

```

(node\__28 is any node page where you want to see all results, I made this basic page)

Now in `html--node--28.html.twig` template, retrieve title of content type = `article`

```
{{ title }}

```
> 2 votes

# Answer
I would highly recommend using views to build simple lists of things where "list" means a list, table, slideshow, or map. It is more maintainable for site builders. This is how you would accomplish this task *without building a module*. In other words, **use views**.

However, here's the custom module route if you want to do it all with code rather than out-of-the-box tools.

Drupal uses a presentation-abstraction-control (PAC) framework, which is similar to model-view-controller (MVC). In Drupal 8 this effectively means you can create a route and route controller to do business logic and then return a render array for the presentation/theming layer to consume.

1. Implement a route and controller in your custom module. You can inject the entity.query service into your controller a few different ways. Then load the entities that you wish via the Entity Query API (similar to an ORM query builder). The controller could also work similar to an entity list builder.
2. Assemble a render array as the return value of the controller. You may want to use render elements or theme functions such as `container` or `table` or `item_list`, but you can implement your own templates with custom variables to use therein.
> 1 votes

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


title: Display image and text above form

text:
# Question
Title: Display image and text above form
I have form built with form api in Drupal 8, now, i want to show an image and some text description on top of that form, meaning, before the form is rendered, what i can think of is, doing a node\_load and then suffix and prefix with the node\_load value or entity load, but my question is, in case i write a function for node\_load or entity\_load, where would i call the return value of these functions and how ? i am thinking of something like this :

```
$form['image_div'] = array(
            '#prefix' => '<div class="image"><img src="path_to_image" />',
            '#suffix' => '</div>',
        );

```

how can i call the path to image here, which is a function return value.

# Answer
Example:

```
 $theme = \Drupal::theme()->getActiveTheme();
 $form['image_div'] = array(
 '#prefix' => '<img src="/' . $theme->getPath() .'/images/smile.png">',
        '#suffix' => '</div>',
    );

```
> 3 votes

---
Tags: forms, 8, media
---


title: How do I access a user image?

text:
# Question
Title: How do I access a user image?
How can I access a user image in Drupal 8? I am trying to use this code, but I am getting an error.

```
$account = \Drupal\user\Entity\User::load($q->uid);
$name = $account->getUsername();
$picture = $account->getUser_picture();

```

# Answer
Use the following snippet to get the user image.

```
$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());
$picture = $user->get('user_picture')->entity->url();

```

If you want to get the default image when the user account doesn't have an image associated, use the following code.

```
$field = \Drupal\field\Entity\FieldConfig::loadByName('user', 'user', 'user_picture');
$default_image = $field->getSetting('default_image');
$file = \Drupal::entityManager()->loadEntityByUuid('file', $default_image['uuid']);
$picture = file_create_url($file->getFileUri());

```
> 5 votes

---
Tags: users, 8, media
---


# Question
Title: Bundle fields for entity without type config entity not created
I have entity that has bundles defined in code(`hook_entity_bundle_info`) and does not use config entity. It also defines fields for each bundle in `\Drupal\Core\Entity\FieldableEntityInterface::bundleFieldDefinitions`. But when I install the module the bundle fields are not created, only the base fields.

According to documentation this is possible and config entity is not needed to provide bundles and fields. So do I have to manually create the fields in `hook_install` or I'm missing something here?

---

If I run the following code only one field will be created out of 11. Strangely that field is my custom field that I've defined in the my module. Others(string, entity reference..) are left out.

```
  $entity_type_id = 'resource';
  $entity_type = \Drupal::entityTypeManager()->getDefinition($entity_type_id);
  $bundles = \Drupal::entityManager()->getBundleInfo($entity_type_id);
  $update_manager = \Drupal::entityDefinitionUpdateManager();

  foreach (array_keys($bundles) AS $bundle) {
    $fields =\Drupal\mymodule\Entity\Resource::bundleFieldDefinitions($entity_type, $bundle, []);
    if (!empty($fields)) {
      foreach ($fields AS $name => $definition) {
        $update_manager
          ->installFieldStorageDefinition($name, $entity_type_id, $entity_type->getProvider(), $definition);
      }
    }
  }

```

---

If I run the following code the fields are present, so it's not an issue with definition.

```
\Drupal::service('entity_field.manager')->getFieldDefinitions('my_type', 'my_bundle');

```

---

I found few references on the internet for hook\_entity\_field\_storage\_info but so far I have no idea what to do with it.

# Answer
This is not answer to the problem I had but a workable solution nonetheless. In the end I have created custom entity per each "bundle" that I have initially planned.

It actually resulted in less tables and also it provided option to handle logic that I have initially planned to do via plugins.

The only drawback of this solution are some route handlers where I have to provide the entity type via option parameter in order to be able to use single handler to get a page title, for example, due to the variable name "restriction" in route handlers.

Also in entity references or entity loader I have to use entity type only instead of entity type and bundle but that's totally fine.

I am using single entity base class, the same forms and so on so not that big of a deal(for now).
> 0 votes

---
Tags: 8, entities
---


title: Inline style fetched from database

text:
# Question
Title: Inline style fetched from database
I'm editing an existing Drupal 7 site, with coloured menu buttons, and each part of the site has the corresponding colours in it's titles and links. For example: the menu item "about us" is coloured orange, and each subpage of "about us" uses orange for it's titles and links.

The problem is: these are all inline styles, fetched from the database table "field\_data\_field\_colour" and printed by a template. I can change the hex-colour values directly in the database, but I've looked everywhere and can't find where to change/set those colours without messing with the database.

# Answer
The pattern `field_data_field_` refers to Field storage. This data is attached to an entity of some kind, most likely a Node. You can learn more about content management on drupal.org, Nodes, content types and fields.

You should edit the node that you want to modify (`admin/content` or click Edit on a node if the tab hasn't been styled out of existence), and find the field that someone added there. Then you can change the value. You can check what fields are used in which entity types by going to `/admin/reports/fields`. Each field usage has a link to its respective Field Management page where you can learn more about how that particular field is configured.

Modifying `field_data_field_` directly in the database is incorrect because data retrieval happens in `field_revision_field_` tables.
> 0 votes

---
Tags: theming, database
---


# Question
Title: Is it possible to use different versions of same language with different prefixes?
I am building a multi language website. I would like to use 2 instances of same language (maybe with slightly different translations).

So is it somehow possible to use different versions of same language with different prefixes?

# Answer
> 4 votes
Yes you can.

Go to the languages settings page (admin/config/regional/language) and click on the *Add Language* link.

There you can select a preexisting language, but below of that list is a *Custom Language* option.

Fill that form with your new language settings and there you have your new language.

To start, I'd suggest to export (admin/config/regional/translate/export) your main language and import it (admin/config/regional/translate/import) in your new language. It will give you a translated new language. Then, you can go to the translate interface and update the texts that must be different.

---
Tags: 7, i18n-l10n
---


title: Global 'Last updated' timestamp

text:
# Question
Title: Global 'Last updated' timestamp
Is there a way to create and display a global 'Last updated' timestamp that would be displayed on every page? 'Last updated' would include adding and changing any piece of content on the website. I know how to display a similar timestamp for each node but I'd like to be able to display just one per page. Maybe looping through all created nodes and finding the latest date? How would I achieve that? Or is there a better solution - looping through all nodes might be memory-intensive, right?

Thanks

# Answer
> 0 votes
If by *"Last Updated"* you are only talking about nodes, then yes, you can.

Create a new view for content (using views module), add a block display, do not filter by any content type, but I think that you can keep the "Published" status. Sort by updated time, descendant, set the pager to show only 1 node. And set the display to only show the updated time. That's all.

---
Tags: nodes, theming
---


# Question
Title: How to filter view by actual name of logged in user matches field?
I'm using Drupal 7 and latest Views. I have a static field set with a variety of names, for a specific view I want to filter if the name of the logged in user matches the actual name of logged in user.

For example if logged in user is "Jean Claude" and I have a field with:

Big Sky, Orange Cat, Jean Claude

I would only want to display the content the field set to Jean Claude.

# Answer
> 0 votes
Using this post: Views: Filtering nodes on the basis of logged in user role I was able to filter with contextual filter based on php query for current user

---
Tags: 7, views
---


title: Display Node Title field in Field group

text:
# Question
Title: Display Node Title field in Field group
I can't find the solution to `print` (display) Drupal's Node Title in a field group? I want my Node Title in the field group (see image).

In this project I can't use Display Suite. I also can't find a template suggestion for a field group?

How do I manage to do this?

# Answer
> 0 votes
A solution would be to install the Display Suite module.

Once both *Display Suite* and *Display Suite UI* modules are enabled you must go to the presentation, choose a layout at the bottom and save, then you will have a lot of fields that weren't available before. One of those fields is the node title.

---
Tags: 7, theming, entities
---


# Question
Title: Rebuild in Features tripping HTTP 500 Error
I am trying to rebuild some features in Drupal 7.37 in preparation for migration and upgrade on a local dev environment using MAMP but I get an HTTP 500 error when attempting to view overrides. Watchdog reports errors with "undefined offset" in schemaorg.features.inc.

Thanks for any help pointing me in the right direction on this one.

# Answer
> 1 votes
This Drupal install was on a local environment using MAMP. The problem was solved when I increased the max\_execution\_time in MAMP's php.ini from 30 to 100.

---
Tags: drush, features
---


# Question
Title: How to upload pdf files and link to them?
I look for a comfortable solution to upload files (pdf) in drupal 8 and link to them (open the link in a new tab). The link I like to embed in a paragraph or apply to lists. Something like entity embed (embedded file). But I do not like the output of this solution.

>

e.g. I can't open the file new window
e.g. I can't change the title of the link

# Answer
I think the solution could be IMCE module which allows you to upload file/images... through CKeditor interface.

> Features
>
> * Basic file operations: upload, delete
> * Image(jpg, png, gif) operations: resize, create thumbnails, preview
> * Support for private file system
> * Configurable limits for user roles: file size per upload, directory quota, file extensions, and image dimensions
> * Personal or shared folders for users
> * Permissions per directory
> * Ftp-like directory navigation
> * File sorting by name, size, dimensions, date
> * Tabbed interface for file operations
> * Keyboard shortcuts(up, down, insert(or enter), delete, home, end, ctrl+A, R(esize), T(humbnails), U(pload)).
> * Built-in support for inline image/file insertion into textareas
> * Multiple file selection(using ctrl or shift)
> * Ajax file operations
> * Themable layout using tpl files
> 2 votes

---
Tags: 8, files
---


# Question
Title: Possible to use OR in contextual filter?
I know with standard filters in Views I can select "AND "OR" etc. for multiple fields but I don't see this option for contextual filters.

# Answer
I think there is a module for that, Views Contextual Filters OR.

> The module provides a views plugin which modify query to support OR conditions for contextual filters.
>
> How does it work?
> The handler is replaced in views which is used by default. A new option will appear in settings page query. If the option is enabled the query will be rewritten using operator OR.
> 1 votes

---
Tags: 7, views
---


# Question
Title: How can create a block that get a field value and render it?
I'm trying to create a simple block that have some link fields. those links have some predefined values and after get any new values from the admin replace with values and then render that values to the theme:
my\_module\src\Plugin\Block\MyBlock:

```
<?php

namespace Drupal\my_modules\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Block\BlockPluginInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;

/**
 * @Block(
 *   id = "my_block",
 *   admin_label = @Translation("My Block"),
 *   category = @Translation("My Block")
 * )
 */
class MyBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    // set default link field value.
    return array(
      'default_LinkA_url' => ('http://www.LinkA.com/'),
      'default_LinkB_url' => ('http://www.LinkB.com/'),
    );
  }

  /**
   * {@inheritdoc}
   */
  public function blockForm($form, FormStateInterface $form_state) {
    // Add a form field to the existing block configuration form.

  $form['block_LinkA_url'] = array(
    '#type' => 'url',
    '#title' => t('Link A:'),
    '#size' => 60,
    '#default_value' => $this->configuration['default_LinkA_url'],
  );
  $form['block_LinkB_url'] = array(
    '#type' => 'url',
    '#title' => t('Link B:'),
    '#size' => 60,
    '#default_value' => $this->configuration['default_LinkB_url'],
  );
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function blockSubmit($form, FormStateInterface $form_state) {
    // Save our custom settings when the form is submitted.
    $this->setConfigurationValue['default_LinkA_url']
      = $form_state->getValue('block_LinkA_url');

    $this->setConfigurationValue['default_LinkB_url']
      = $form_state->getValue('block_LinkB_url');
  }

  /**
   * {@inheritdoc}
   */
  public function build() {
    return (
      '#markup' => $this->configuration['default_LinkA_url'],
      '#markup' => $this->configuration['default_LinkB_url'],
    );
  }
}

```

whatsoever I try I cant get any result, I would be happy to hear what the problem is.

# Answer
If you use `setConfigurationValue()`, put the value as parameter in the function:

```
$this->setConfigurationValue('default_LinkA_url', $form_state->getValue('block_LinkA_url'));

```

Or better set the value in the configuration array like this:

```
$this->configuration['default_LinkA_url'] = $form_state->getValue('block_LinkA_url');

```

To display the url use the render element `link`:

https://api.drupal.org/api/drupal/core!lib!Drupal!Core!Render!Element!Link.php/class/Link/8.2.x
> 2 votes

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


title: Currency conversion for paypal

text:
# Question
Title: Currency conversion for paypal
I have integrated paypal payment using the Ubercart 7.x-3.6 module in my website.

My store currency is Rs(INR). Now I have 1500 Rs in a cart When I am proceeding to checkout on paypal its showing 1500 USD.

Isn't it possible that the amount converts in equivalent USD automatically?

If not, then how can I convert it from INR to USD?

# Answer
Please check this out. It is a workaround for converting the currency on checkout https://www.drupal.org/node/789284
> 0 votes

---
Tags: ubercart, payment-gateways
---


# Question
Title: Taxonomy shows term ID not term name in Facet API
Im trying to facet by taxonomy fields but I see just the ID, not the name of the term, why?

I'm getting this:

```
3 (76)
4 (35)
176 (7)
167 (6)
177 (5)
168 (4)
5 (2)
163 (1)
7 (1)

```

and it should be

```
Casa (76)
Depto (35)
Duplex (7)
...

```

Any ideas?

# Answer
in

```
  admin/config/search/facets/your_facet_name/edit

```

you must select :

```
  List item label
 Translate entity label

```
> 2 votes

# Answer
This can happen if you delete terms that are associated with nodes.

Read this long discussion on Drupal.org: https://www.drupal.org/node/1421378
> 0 votes

---
Tags: search
---


title: Remember add to cart form state

text:
# Question
Title: Remember add to cart form state
Is there a way to remember the chosen product attribute on the add to cart form? I have a product with a couple of options. If the users selects one on the product page and goes to another page, the form will reset and selects the first option again.

# Answer
> 0 votes
You can store it in session

During Add to cart.

```
$_SESSION['my_module_name']['product_id']['field_name'] = $filter_value

```

Then set form option value from session

```
function my_module_name_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'your_form_id') {
    $get_default_value = isset($_SESSION['my_module_name']['product_id']['field_name'])?$_SESSION['my_module_name']['product_id']['field_name']:'';
    $form['field_name']['#default_value'] = $get_default_value;
  }
}

```

---
Tags: commerce
---


# Question
Title: Mixing field collection items with regular fields in views
I've got a content type that contains fields like this:

```
title
field collection
body
link

```

The field collection contains:

```
image
text

```

The field collection is going to be for 3 iterations in one node. In views this is the desired output:

```
title
field collection 1 image
field collection 1 text
field collection 2 image
field collection 2 text
field collection 3 image
field collection 3 text
body
text
link

```

I've set the relationship in views and retrieved the field collection fields. The problem I'm running into is it's duplicating all the single fields for every field collection item. The output looks like this:

```
title
field collection 1 image
field collection 1 text
body
text
link
title
field collection 2 image
field collection 2 text
body
text
link
title
field collection 3 image
field collection 3 text
body
text
link

```

How can I get it to draw all the field collection fields without duplicating the rest of the fields along with it?

# Answer
> 1 votes
I think this is not the right views set-up for what you want to display, you have done wrong field selections. To see direct solution scroll down to Solution section.

---

# What is the Issue:

If you see your views field setting it is like as follows,

* Content: title
* field collection item: Bubble title
* field collection item: Bubble image
* Content: Body
* Content: Link

So, here in above view set-up the `field collection item` is just one field, so through views you are just accessing one field, hence, the concept of field collection module dies here. Here, it is just a field which you are accessing through the `Relationship`.

## Now, why you are observing what you are observing in the view,

**Your Node:** Following is the correct representation of your Node, Not what you have shown in your Question. Your node has FIVE main fields- and whatever inside the field collection field are field-in-field.

```
   1. title
   2. field collection
     2.1a field collection 1 image
     2.1b field collection 1 text
     2.2a field collection 2 image
     2.2b field collection 2 text
     2.3a field collection 3 image
     2.3b field collection 3 text
   3. body
   4. text
   5. link

```

Now, you have set your views like as follows,

```
   1. Content: title
   2.xx field collection item: Bubble title
   2.xx field collection item: Bubble image
   3. Content: Body
   4. Content: Link

```

I think by this time you would have understood why you are getting what you are getting in views.

Let me explain:

**Cycle:1** Views start the first cycle and iterates from its Fiest field to Fourth field, so it will showing following fields:

```
   1. Content: title
   2.1a field collection item: Bubble title
   2.1b field collection item: Bubble image
   3. Content: Body
   4. Content: Link

```

**Cycle:2** Now, views works stops there, But wait, Views discover that another 2.xx and 2.xx are there on node, So it starts second cycle so again from TOP to Bottom,

```
   1. Content: title
   2.2a field collection item: Bubble title
   2.2b field collection item: Bubble image
   3. Content: Body
   4. Content: Link

```

**Cycle:3** Then again third cycle, So that why you are getting this,

```
   1. Content: title
   2.3a field collection item: Bubble title
   2.3b field collection item: Bubble image
   3. Content: Body
   4. Content: Link

```

So whatever views are showing it showing correct as per your field selection, But that is not what you want, please see the solution in following section, it is very simple.

---

# Solution:

The solution is very simple: *You just need a field which represent the entire field collection of that node and luckily that is present in views.*

* Remove the relationship: You do not need the relations ship.
* Modify the field: Instead of selecting individual field, select entire field collection which you can find as Content:nameOfFieldCollection. in my case it is FC101.

>

Example:

I have created Content type with:

```
1. Title
2. Body
3. Field collection(FC101)
   - Image
   - text
   - Image
   - text
   - Image
   - text
4. Body2

```

**My views set-up:**

>

**Output in VIEW:**

```
1. Title
2. Body
3. Field collection(FC101)
   - Image
   - text
   - Image
   - text
   - Image
   - text
4. Body2

```

---
Tags: views, entities
---


# Question
Title: how to deploy from dev to staging and production?
Hello so here is my question, I have three environments for my drupal 7 installation **Dev, Staging, Production**, right now Dev has all the new code and well everything is setup there. The move of the code from Dev to Sta or Prod is quite simple as it is just code and can be done with a simple push. But what about the configuration on the DB? how do you move DB configuration from Dev to Sta and Prod? more specifically how do you sync the configuration from Dev to Sta or Prod? so the views, nodes and whatever modules you had enabled on Dev will show on Sta or Prod?

Tried features and well it moved the code (which i already know how) but the db configuration was not transferred/enabled in the other environment

# Answer
> 1 votes
Any deployment strategy can be broken down primarly into three main streams

* Content(Node,taxonomies etc.)
* Code
* Configuration(Content types, Vocabularies etc.)

**Content Deployment**

I am assuming you are not targeting content deployment as part of your deployment. Its a complex peace based on your content strategy.

**Configuration Deployment**

Configuration Deployment, since content and configuration are kind of tightly coupled till Drupal 7, there is no way out of the box you can just keep the configurations in sync. But there are couple of modules which let you pull your configuration into code, features is definitely one and I believe most widely used module for deployment. Sometime you can not get all the configurations just by features module, there is another helper module strongarm module which will let you exporting variable configurations by contributed module.

Just wanted to bring the keypoints for feature module.

* Features module let you bring the configuration in code.
* Either you update your feature or revert your feature based on if you want to get the configurations as in feature code and revert any manual override configuration we do feature revert, if you want to get the manual updated configuration in feature code we do feature update/recreate.
* Feature module compares the configuration in code and configuration in database, based on it features allow to revert/update.

**Code Deployment**

For code any versioning tool will do the job.

---
Tags: deployment
---


# Question
Title: How do I print the term names associated with a node?
I want to show the term names used in a node. My term field machine name is field\_category.

```
$query = \Drupal::entityQuery('node');
$query->condition('status', 1);
$query->condition('type', 'content_type');
$entity_ids = $query->execute();
$nodes = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($entity_ids);
foreach ($nodes as $node) {
   dpm($node);
}

```

`dpm()` prints the following.

```
stdClass Object(
[__CLASS__] => Drupal\node\Entity\Node
[in_preview] =>
[values] => Array
 [field_category] => Array
            (
                [x-default] => Array
                    (
                        [0] => Array
                            (
                                [target_id] => 4
                            )

                        [1] => Array
                            (
                                [target_id] => 2
                            )

                    )

            )

```

How can I print the term names as *term-1,term-2*?

# Answer
You can do this:

```
foreach($nodes as $node) {
  $categories = $node->field_category->referencedEntities();
  foreach($categories as $category) {
    print_r($category->getName(). ",");
  }
  print("\n");
}

```
> 3 votes

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


title: Get data from database

text:
# Question
Title: Get data from database
I'm running Drupal 7 site on WAMP Server!

I'm using below code in a custom block to get data from the database :

```
$result = db_select('event', 'x')
  ->fields('x', array('address'))
  ->execute()
  ->fetchAll();
foreach ($result as $value) {
  print_r ($value);
}

```

***Event*** *is the name of node we use*

Every time I try to reload the page, I get this message :

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

When I check WAMP PHP error log, there is nothing in it about it !

Any idea ?

**Update :** Now is see I get this error :

```
PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'drupal.event' doesn't exist: SELECT x.address AS address FROM {event} x; Array ( ) in eval()

```

I understand that it mean it can't find the table, but why ? I found it like that in every example on the internet !

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

Above error is Drupal specific error, to get more details about this error you need to go to Drupal Logs. You can access Drupal Logs by navigating to "**Admin =\> Reports =\> Recent Log Messages**". These logs are provided by Database logging Module in Drupal Core.

**Updates:**

> **Event** is the name of node we use

In Drupal Nodes data is stored into **node** table and not table named with content type. Check out getting started guide about node. *You've to check **node** table to get all nodes where **type** is event.*

To fetch nodes you can use EntityFieldQuery API. Check example on How to use EntityFieldQuery. And to fetch any fields value, check **Programmatically get field values**.
> 2 votes

---
Tags: 7, database
---


title: Problem extending BookNavigationBlock

text:
# Question
Title: Problem extending BookNavigationBlock
i have a Problem extending a BookNavigationBlock Plugin. When I extend BlockBase it works, but when trying to extend BookNavigationBlock, it fails when placing the block, without any error messages. What am I missing here? (The Code is inside modules/ifg\_book\_navigation/src/Plugin/Block/IfgBookNavigationBlock.php)

```
namespace Drupal\ifg_book_navigation\Plugin\Block;

use Drupal\book\Plugin\Block;
/**
 * Provides a fully expanded 'Book navigation' block.
 *
 * @Block(
 *   id = "ifg_book_navigation",
 *   admin_label = @Translation("Expanded Book navigation"),
 *   category = @Translation("Menus")
 * )
 */
class IfgBookNavigationBlock extends BookNavigationBlock {

  /**
   * {@inheritdoc}
   */
  public function build() {
    return array(
      '#markup' => $this->t('Hello, World!'),
    );
  }
}

```

Thanx!

UPDATE: I could trace the Problem to the Plugin Factory. In the getPluginClass method of DefaultFactory it is checked if the class exists:

```
if (!class_exists($class)) {
  throw new PluginException(sprintf('Plugin (%s) instance class "%s" does not exist.', $plugin_id, $class));
}

```

The value of $class is Drupal\ifg\_book\_navigation\Plugin\Block\IfgBookNavigationBlock which seems to be correct. However class\_exists() itself seems to fail, not even returning false. This could have something to do with autoloading, as by default class\_exists() tries this by default ...

UPDATE: It seems like the behaviour is the same for other existing blocks, just tested UserLoginBlock

# Answer
> 1 votes
The actual class has to be included in the `use` statement.

```
use Drupal\book\Plugin\Block\BookNavigationBlock;

```

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


# Question
Title: Why /Drupal\Core\Form\FormBuilder->renderPlaceholderFormAction is taking so long?
I'm profiling drupal 8 website in New Relic

Report shows me that method:

> /Drupal\Core\Form\FormBuilder-\>renderPlaceholderFormAction

takes ~2sec.

This method is called in:

> \Drupal\Core\Render\Renderer-\>doRender

Code related to execution:

```
// Build the element if it is still empty.
if (isset($elements['#lazy_builder'])) {
  $callable = $elements['#lazy_builder'][0];
  $args = $elements['#lazy_builder'][1];
  if (is_string($callable) && strpos($callable, '::') === FALSE) {
    $callable = $this->controllerResolver->getControllerFromDefinition($callable);
  }
  $new_elements = call_user_func_array($callable, $args);
  // Retain the original cacheability metadata, plus cache keys.
  CacheableMetadata::createFromRenderArray($elements)
    ->merge(CacheableMetadata::createFromRenderArray($new_elements))
    ->applyTo($new_elements);
  if (isset($elements['#cache']['keys'])) {
    $new_elements['#cache']['keys'] = $elements['#cache']['keys'];
  }
  $elements = $new_elements;
  $elements['#lazy_builder_built'] = TRUE;
}

```

Method code:

```
 /**
   * #lazy_builder callback; renders a form action URL.
   *
   * @return array
   *   A renderable array representing the form action.
   */
  public function renderPlaceholderFormAction() {
    return [
      '#type' => 'markup',
      '#markup' => $this->buildFormAction(),
      '#cache' => ['contexts' => ['url.path', 'url.query_args']],
    ];
  }

 /**
   * Builds the $form['#action'].
   *
   * @return string
   *   The URL to be used as the $form['#action'].
   */
  protected function buildFormAction() {
    // @todo Use <current> instead of the master request in
    //   https://www.drupal.org/node/2505339.
    $request = $this->requestStack->getMasterRequest();
    $request_uri = $request->getRequestUri();

    // Prevent cross site requests via the Form API by using an absolute URL
    // when the request uri starts with multiple slashes..
    if (strpos($request_uri, '//') === 0) {
      $request_uri = $request->getUri();
    }

    // @todo Remove this parsing once these are removed from the request in
    //   https://www.drupal.org/node/2504709.
    $parsed = UrlHelper::parse($request_uri);
    unset($parsed['query'][static::AJAX_FORM_REQUEST], $parsed['query'][MainContentViewSubscriber::WRAPPER_FORMAT]);
    return $parsed['path'] . ($parsed['query'] ? ('?' . UrlHelper::buildQuery($parsed['query'])) : '');
  }

```

I don't get it at all. This is basic method, no rocket science and 2 sec of execution :(

New Relic output:

# Answer
Pretty sure that report is bogus.

That's just an arbitrary method, not a controller. They somehow identify that as the controller for that request but of course that doesn't make sense. That page lists transactions, so complete requests, not single method calls. So some requests take 2s which it incorrectly identifies as this.

Looks like new relic still can't reliably detect the route/controller for a request. Try our new relic module: https://www.drupal.org/project/new\_relic\_rpm. It reports the route name for the controller, then you'll see what kind of request this actually is.
> 4 votes

---
Tags: 8, performance
---


title: Insert html in views every nth element

text:
# Question
Title: Insert html in views every nth element
I want to insert `<div class="clearfix"></div>` every nth element. How can I insert this into the twig template of a view?

Same Question for D7: Insert \*whatever\* every nth row in Views

# Answer
> 4 votes
In twig you can use `|batch()`.

For example to group the view in groups of 5 and add a div container around each group:

**views-view-unformatted.html.twig**

```
{% for group in rows|batch(5) %}
  <div class="group">
  {% for row in group %}
    <div{{ row.attributes }}>
      {{ row.content }}
    </div>
  {% endfor %}
  </div>
{% endfor %}

```

---
Tags: 8
---


# Question
Title: Properly adding an action to a ContentEntityForm
I've created an add/edit form for a custom entity type, which extends `Drupal\Core\Entity\ContentEntityForm`. By default this form always comes with a "Save" button, and a "Delete" button if editing. I've been asked to add a "Cancel" button as well, but can't figure out how this is supposed to be done in Drupal.

I've seen plenty of answers about using `hook_form_alter()`, but nothing that is really working. My current solution is to add

```
$form['cancel'] = array(
    '#type' => 'submit',
    '#weight' => 10001,
    '#submit' => array('cancel_submit'),
    '#value' => t('Cancel'),
);

```

to the form's `form()` function, where `cancel_submit()` is a custom function, but that renders like  which looks awful.

How can I get the two buttons to be in line with each other? Is there a way to properly add a button to the form actions?

# Answer
> 5 votes
This is relatively simple when you define the form class yourself and one of the reasons Drupal 8 has gone all out on OOP. What you need to do is to extend the form class and implement the `::actions` method. This would look like this:

```
class CustomEntityForm extends ContentEntityForm {
  ...

  protected function actions(array $form, FormStateInterface $form_state) {
    $actions =  parent::actions($form, $form_state);
    $actions['cancel'] = [
      '#type' => 'submit',
      '#value' => $this->t('Cancel'),
      '#submit' => ['::cancelSubmit'],
    ];
    return $actions;
  }

  public function cancelSubmit($form, FormStateInterface $form_state) {
    // Du custom submit validation
  }

}

```

You could also achieve this with normal form alter, but would need to place the submit button inside the actions element, which is usually called `actions`, fx

```
$form['actions']['cancel'] = array(
  '#type' => 'submit',
  '#weight' => 10001,
  '#submit' => array('cancel_submit'),
  '#value' => t('Cancel'),
);

```

---
Tags: forms, 8, entities
---


# Question
Title: How do I download an image/file to a specified location on the disk?
I want to provide the functionality to the users to download the images/files to their system but not with direct download but with a dialog where they tell the location where they want to download the image.

I have tried the download\_file and file\_force modules. Both modules provide the field formatter to download the image. but when the user click on the download link the the image directly downloads, it does not provide the option to the user to specify a location for the image to be downloaded in.

Is there any other module or any other method?

# Answer
This behavior is largely up to browser itself, and this can't be controlled over how the browser has been configured.

Above settings are from **Google Chrome** browser. If user has checked "*Ask where to save each file before downloading*" checkbox, then browser will prompt to choose location else download to default location set in "*Download Location*".

Instead try educating the user before they download. That's the best way.

Ref : Prompt user to save file to a specific location
> 2 votes

---
Tags: 7, files
---


# Question
Title: Theme template.php functions after bootstrap
I'm trying to print a drupal menu outside drupal. In order to achieve this I ran the bootstrap as follows:

```
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

```

And I render my menu as follows:

```
public static function getDrupalMenu($menuName) {
        $menu_output = &drupal_static(__FUNCTION__, array());

        if (!isset($menu_output[$menuName])) {
        $tree = menu_tree_all_data($menuName);
        $menu_output[$menuName] = menu_tree_output($tree);
        }
        return render($menu_output[$menuName]);
    }

```

Which is basically just a copy of the `menu_tree` function AND with menu\_tree\_all\_data instead of menu\_tree\_page\_data so I get all links no matter what page I'm on.

Everything works fine so far, my menu is printed, everybody is happy... but unfortunately my links are incorrect somehow. To solve this I've used a solution for absolute links as described here:

How to force absolute links on a menu tree in Drupal 7

So I use:

```
function mythemename_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'], $element['#href'], array_merge($element['#localized_options'], array('absolute' => TRUE)));
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

```

**This works fine on my drupal site**, but where I call the getDrupalMenu() after initializing the bootstrap it does not work (empty result, not even the original one). I probably have to set the theme or something, but I can't find what or where to do so.

Just to be clear: when I change the code in core (menu.inc) is works fine on both sites... it just gives en empty result when I override it in the theme.

Any pointers or solutions ?

# Answer
While what you are doing could work, this is not what you want to do. If you want to render your menus outside Drupal you should do it a more robust way to implement this using Drupal best practice etc.

One way would be to

* create a public URL that returns the menus. This could return just the data or markup.
* Have you custom code consume the API, so you fetch the data via http instead of manually trying to bootstrap Drupal.

You also need to ask yourself why this custom code lives outside Drupal. If you can bootstrap Drupal etc, the code might as well be part of Drupal via a module.

Boostrapping Drupal yourself is possible but a lot of crazy bugs can show up. Drupal depend on a lot of various stuff like $\_GET / $\_POST and other stuff that you might forget to handle. Also if you update Drupal this code can easily break as you are using internal functions which can change in various ways.
> 0 votes

---
Tags: theming, navigation, bootstrapping
---


title: Render link elements in blocks?

text:
# Question
Title: Render link elements in blocks?
I'm trying to create a simple block that have some link fields. those links have some predefined values and after get any new values from the admin replace with values and then render that values to the theme:
my\_module\src\Plugin\Block\MyBlock.php:

```
<?php

namespace Drupal\my_modules\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Block\BlockPluginInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;

/**
 * @Block(
 *   id = "my_block",
 *   admin_label = @Translation("My Block"),
 *   category = @Translation("My Block")
 * )
 */
class MyBlock extends BlockBase {

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    // set default link field value.
    return array(
      'default_LinkA_url' => ('http://www.LinkA.com/'),
      'default_LinkB_url' => ('http://www.LinkB.com/'),
    );
  }

  /**
   * {@inheritdoc}
   */
  public function blockForm($form, FormStateInterface $form_state) {
    // Add a form field to the existing block configuration form.

  $form['block_LinkA_url'] = array(
    '#type' => 'url',
    '#title' => t('Link A:'),
    '#size' => 60,
    '#default_value' => $this->configuration['default_LinkA_url'],
  );
  $form['block_LinkB_url'] = array(
    '#type' => 'url',
    '#title' => t('Link B:'),
    '#size' => 60,
    '#default_value' => $this->configuration['default_LinkB_url'],
  );
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function blockSubmit($form, FormStateInterface $form_state) {
    // Save our custom settings when the form is submitted.
    $this->configuration['default_LinkA_url'] = $form_state->getValue('block_LinkA_url');
    $this->configuration['default_LinkB_url'] = $form_state->getValue('block_LinkB_url');
  }

  /**
   * {@inheritdoc}
   */
  public function build() {
    return [
      '#markup' => $this->configuration['default_LinkA_url'],
      '#markup' => $this->configuration['default_LinkB_url'],
    ];
  }
}

```

Whatsoever I try I can't get any result, and this code only show one link like below:
`http://www.LinkA.com` (a plain text only)

but what I want to achieve is some think like This:
**Link A**
This Link has Some CSS Style and Open in new page rater than being a plain text like above link.
I would be happy to hear what the problem is.

# Answer
> 1 votes
You have to build a render array like this:

```
   public function build() {
     $build = [];
     $build['linkA'] = [
       '#type' => 'link',
       '#title' => 'Link A',
       '#attributes' => [
         'class' => 'link-class',
         'target' => '_blank',
       ],
       '#url' => Url::fromUri($this->configuration['default_LinkA_url']),
     ];
     $build['linkB'] = [
       // ...
     ];

     return $build;
   }

```

You can add attributes to the link, classes for css or a target to open it in a new tab.

---
Tags: theming, 8, entities, blocks, navigation
---


title: How to create multi login pages

text:
# Question
Title: How to create multi login pages
I have enabled the "User Login" block inside the Content Region and configured it to show on two specific Views which should be password protected.

I have also created two Views and two different access roles for each view.

After I access the password protected pages as anonymous user, I can see both Login screens and authentication on one page works but refreshing the second page shows:

```
Access denied
You are not authorized to access this page.

```

Also if I authenticate on page A with login for page B, I get the same message but refreshing page B shows the content.

Could this be a cookie related issue, because I have to clear my browser cookie to logout. Does Drupal only allow one login cookie?

# Answer
I tackle this with Panels.

Instead of having a view as a page, I make a new Panel page. Then I add two variants. For authenticated users, the content has the view, normally configured as a separate panel-pane display. For anonymous users, the variant just has the login block and sometimes a custom content pane that has a brief message.
> 0 votes

# Answer
You can use Role login page module to create multiple login pages.
> 0 votes

---
Tags: 7, users
---


# Question
Title: Use wget to mirror a site to a static site
I'm trying to use the following command to mirror a Drupal 6 site which needs to be archived as a static site. Unfortunately, I've only been able to find a static generator for Drupal 7, not 6. I'm having issues because it seems that

1. By logging in as different roles, the wget command will pull down completely different directory structures. This is not unanticipated, but in some cases as an administrator there is quite a lot of content missing which is pulled down with accounts that have lesser permissions.
2. There are links on the main page in separate blocks whose directory and pages do not get pulled down in the file directory structure by logging in with any role, including administrator.

So far I've successfully been able to mirror the site (with the above limitations), but I'm not sure if the command is actually mirroring the entire site as I need it to do. Here is the code I am using for `wget`:

```
wget --mirror -w 2 -p --convert-links --load-cookies cookies.txt -e robots=off https://url.org/user

```

where the cookies file is created like this:

```
wget --save-cookies cookies.txt --post-data 'name=MY_USERNAME&pass=MY_PASSWORD&form_build_id=FORM_ID&form_id=user_login&op=Log+in' https://url.org/user

```

I am very new to Drupal, so am not sure how roles and permissions, or the structure of the content might affect a `wget mirror` operation. Any suggestions would be appreciated!

# Answer
> 1 votes
It appears that the issue had to do with the fact that a "Logout" block was in the header of the main site. As a result, when wget went to pull things down, it would actually go to the logout link, and thus the rest of the files would either display a login screen or wouldn't be downloaded. By disabling the logout block OR adding --reject logout to my wget command, it seems to have fixed the issue and now the full directory structure is being downloaded. The command I ended up using was:

```
wget --mirror -w 2 -p --convert-links --load-cookies cookies.txt -e robots=off --reject logout https://url.org/user

```

# Answer
> 1 votes
```
wget -mnH -k --html-extension https://example.com

```

I'm not setting any cookies, but this is what I usually run to mirror a website and it works well. You can sub the last portion if you don't want html extensions

---
Tags: 6, blocks, navigation
---


# Question
Title: What does the option "Enable Display field" shown when creating a new file field do/mean?
What does the option *Enable Display field* shown when creating a new file field do/mean?

# Answer
> 4 votes
It will provide you an additional option whether you want to display the attached file or not. As you can see the description provide under that option in following image.

>

Now enabling it, will add `check box option` to content editing layer as you can see in following image.

`Include file in display`

>

So, if you check it will show the file in final display and if you uncheck it will not show the file.

Hence, it provides one extra quick option to author whether they want to show the attached file or not other-wise previously they had to go back and delete entire file from the content and again if they want to put they have to again upload and insert. Here, it is like On-Off Switch.

---
Tags: 8, entities
---


# Question
Title: Drush Site Install does not populate table prefix
```
sudo drush site-install standard -y --db-prefix='alaska_' --db-su='postgres'
--db-url=pgsql://drupaldbuser:password@localhost:5432/drupal
--account-name='admin' --account-pass='admin' --site-name='alaska'
--sites-subdir='alaska.jobcorps.gov'

```

This command does not populate the database with tables that have the table prefix. This prevents us from installing Drupal 8 multi-site on a single database using Drush.

I've tried renaming the tables and then proceeding with the next sub-site install. This fails because drush drops all tables when it runs subsequent installs on the same database.

I've also tried

```
install_settings_form.pgsql_prefix='alaska_'

```

Tried multiple versions of Drush. Currently on `9.0-dev` to see if that has a fix in it.

# Answer
> 0 votes
For the problem of dropped tables, you can use --db-drop-existing-tables=FALSE.

I'm looking for an answer to the prefix problem too ...

---
Tags: multi-sites
---


# Question
Title: Why do I get the "Class 'Drupal\Core\Database' not found" error?
I am using the following code.

```
$conn = Database::getConnection();
$conn->insert('testimonial')->fields(array('name' => $form_state->getValue('name')))->execute();

```

I get the following error:

> Class 'Drupal\Core\Database' not found

I am using `use Drupal\Core\Database;`. What is wrong in my code?

Update: i find using namespaces a problem, like now i want to get row count, if insert was successfull or not. i tried with

```
$result->allowRowCount = TRUE;
if ($result->rowCount() == 0) { }

```

and for rowcount i added the name space use Drupal\Core\Database; i get

> Cannot use Drupal\Core\Database as Database because the name is already in use in

and if i remove this . i get

> Call to undefined method Drupal\Core\Database\Driver\mysql\Connection::rowCount()

How to use namespaces exactly. like i am assuming if i do

> use Drupal\Core\Database

then all the classes in that namespace and all the children namespace should get inehrited. Is this right ?

# Answer
> 7 votes
`Drupal\Core\Database` is the namespace of the class, which is not what the `use` statement requires. It needs the full-qualified class name, which, for that class, is `Drupal\Core\Database\Database`.

```
use Drupal\Core\Database\Database;

```

That is what Drupal core uses, for example in the DbLog.php file.

```
namespace Drupal\dblog\Logger;

use Drupal\Component\Utility\Unicode;
use Drupal\Core\Database\Connection;
use Drupal\Core\Database\Database;
use Drupal\Core\Database\DatabaseException;
use Drupal\Core\DependencyInjection\DependencySerializationTrait;
use Drupal\Core\Logger\LogMessageParserInterface;
use Drupal\Core\Logger\RfcLoggerTrait;
use Psr\Log\LoggerInterface;

```

---
Tags: 8, database
---


# Question
Title: Creating multiple destinations from one source
I'm writing a Drupal 8 migration from a non-Drupal site where I need to migrate news articles that have inline images in them, sometimes more than 10. I've figured I'll do this in two steps:

1. A migration for creating file entities for each image present in the source node body.
2. A migration that creates news article entities, and for each image encountered, look up the file entity that was created in the 1st migration and use the File Usage API to indicate the file is used in this node.

My problem is the first migration. The Migration API wants to map a single source to a single destination. I need to be able to map a single source to MULTIPLE destinations, since I will be creating as many as 10 file entities from this single source row.

Does anyone know if this is possible, and if so, are there any examples in core or contrib migrating like this?

If I can't find a way to do it this way, I'll instead just migrate everything in the same single migration, and create the file entities on the fly. I'll just have to write a custom rollback implementation to remove them as well.

# Answer
> 0 votes
I usually use D7 migrate. But from what i've read of D8 either of these approaches should work:

> My problem is the first migration. The Migration API wants to map a single source to a single destination.

## Option 1

In migration 1 simply import any encountered file into drupal. Then record the `file id` to a custom table of columns `legacy_url, old_source_id, drupal_file_id` for example in the complete() method of the migration.

In your second migration pass an array of `drupal_file_id` to your Node's file field from a `select drupal_file_id from mytable where old_source_id = $old_source_id`. This will attach the legacy files into the new Node. You may need still need to adjust any inline usage of images, or just use a view\_mode to show the file list in D8.

## Option 2

Just import articles (don't use a 1st migration for just files) and use `complete()` method in a migration to scan the HTML using `DomDocument` or `simple_html_dom` to find file urls and use the drupal API to save the remote file to drupal and then update the DOM with the new url. Create a custom rollback function to remove these files if needed.

### Edit

Some example Drupal 8 file migration logic and classes can be seen at the following link. This may not address your exact issue, but in my opinion is good reference. http://www.jeffgeerling.com/blog/2016/migrating-20000-images-audio-clips-and-video-clips-drupal-8

---
Tags: 8, migrations
---


# Question
Title: Using Rules How can I Remove a role from ANY user not just current user
I have a use case for a project where a user of specific role has access to the site during specific dates. What I want to occur is- when the date passes the user loses his role and access to the site.

Currently, I have this rule working on Cron run, but the only option to me is to react on site:current-user. Is there a way to react on ANY user?

# Answer
A possible approach to make this work, is to *process the results of a VBO enabled view via Rules*, whereas your rule performs 2 Rules Actions:

* load the VBO list of users that you want to be processed.
* add a loop to perform a Rules Action, probably similar to the rule you already have in place, for each user contained in your Views results.

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

---
Tags: users, rules
---


title: How to modify the registration form?

text:
# Question
Title: How to modify the registration form?
I need some help adding text to the bottom of the registration form. I've never modified the registration form before and I did not set up this site. Bootstrap Modal is being used for the form. Here is a screen capture of it:

The content needs a check box that must be checked for the submit button to work. Is there a module that can help, or, how do I locate this form to do some modifications?

# Answer
You can always alter any form by hook\_form\_alter,in your case it would be somewhat closer to following

```
// Implements hook_form_form_id_alter().
function my_module_name_form_user_register_form_alter(&$form,&$form_state) {
  $form['help_text'] = array(
    '#markup' => 'Your help text will go here',
    '#weight' => $form['mail']['#weight'] + 1; // Or could be a fix value.
  );
}

```
> 1 votes

---
Tags: forms, users
---


# Question
Title: How do I add a favicon to my custom theme?
This seems like a simple question, but I couldn't find a clear answer when I googled so going to create one.

# Answer
You can add a favicon by just adding a favicon.ico (or .png or .gif or other valid favicon file type) to the root of your custom theme folder.

If you'd like to have your favicon stored in a custom location, see the method described here: (Change default favicon programmatically)

Edit:

If you simply want to give your theme the ability to change the favicon, without providing one yourself, you can add the setting to your theme settings folder by adding a /config/install/THEMENAME.settings.yml file to your theme, with the following settings:

```
features:
  favicon: true
favicon:
  use_default: false

```
> 5 votes

---
Tags: theming, 8
---


# Question
Title: How to programmatically know a required select list has no value on node add/edit form page?
For a required field using select list widget, if there is no options, the field will show only one "-Select one-" value on the node add/edit form page. So, how to know that by coding?

# Answer
It will depend on the field type. For a list field with text/numeric values, the output of the field API function `field_info_field()` contains allowed values within its `settings` element. This field data can be fed into `list_allowed_values()` to retrieve either the static or dynamic list of allowed values for the field.

For example:

```
$field = field_info_field('field_myfield');
$values = list_allowed_values($field);
if (count($values) > 0) {
  // There are allow values
}
else {
  // There are no allowed values
}

```
> 0 votes

---
Tags: forms
---


# Question
Title: How to map Feed Importer with my content type?
Here's my problem:

I'm using the "Feeds" module to import data from different RSS feeds. One of the feeds is:

```
http://www.happynews.com/rss/.aspx

```

As you can see, one of the elements is the "link" of each article.

How do I map that link with my content type? (note it's NOT the feed's link)

I've updated my content type "Feed item", adding a new text field to it called "Article link", attached it to the importer item and definitely can see the new field in the "target" options, however, it seems that in the "source" options there is no link field.

Is there a way to add "source" options to map them up with our targets?

Big thanks in advance for any help! I really appreciate it.

So far I found this article that might help to my problem above:

# Answer
> How do I map that link with my content type? (note it's NOT the feed's link)

You're right your feed link is NOT a feed link. The URL is simply incorrect and this issue has nothing to do with Feeds module.

`http://www.happynews.com/rss/.aspx` returns 404 but when you dig a little you can quickly find that `http://www.happynews.com/rss/` returns directories and other resources containing XML feeds.

For example https://www.happynews.com/rss/environment.aspx is a correct RSS channel titled "HappyNews - Environment" where you can see `<item>` XML nodes and each nested `<title><description><link><pubDate>` data.

To import such single channel you need:

* create importer with **HTTP Fetcher**
* and as a parser check **Common syndication parser** option
* in fetcher settings you should provide RSS source channel link, so in **Automatically add scheme** input simply paste link to the channel you want to import like `https://www.happynews.com/rss/environment.aspx`
* if right address is given Feeds **fetcher** will be able to"recognize" the scheme and all accessible fields should be visible on **mapping** tab in "Select a source" select field.

After all steps inluding RSS -\> node fields mapping definitions you will be able to import data periodically (when CRON configured) or manually by running `http://you-site-address/import`

You can also attach importer to specific content type, this way source is imported by creating a node of that content type. .
> 1 votes

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


title: Views template files not working

text:
# Question
Title: Views template files not working
I have two template files for a view but only one of them is getting picked up. If I look under the Theme dialog for the view I can see that my two theme files are bolded.

The Display Output template file is working but the Row Style is not working. I've also added this to my template file to try try and get it to work but I don't think it's doing anything.

```
function mytheme_preprocess_views_view(&$variables){
  if ($variables['view']->name == 'travel_extras_hotel_carousel') {
    $variables['theme_hook_suggestions'][] = 'views_view_fields__travel_extras_hotel_carousel__block';
    $variables['theme_hook_suggestions'][] = 'views_view__travel_extras_hotel_carousel__block';
  }
  return $variables;
}

```

Does anyone have any ideas about what else I could do?

I'm using views 3.3

# Answer
> 1 votes
Best way to learn something new about your project is not to ask "what is going on" but do own investigation. Try to debug as much things as possible. You can start by enabling **Theme debug mode** This is great feature implemented as of version 7.33

As Drupal documentation states:

> As of Drupal 7.33, Drupal core has a theme debug mode that can be enabled and disabled via the theme\_debug variable. Theme debug mode can be used to see possible template suggestions and the locations of template files right in your HTML markup (as HTML comments).

Place `$conf['theme_debug'] = TRUE;` variable in your settings.php file and use Developer Tool (F12) in your browser or any other tool that can help you see source HTML markup.

With theme debug mode you will be able to see all template suggestions and what *tpl* file was chosen to rendering. If your *tpl* file is really rendered you should see something like:

`<!-- BEGIN OUTPUT from '(...)/views-view--travel-extras-hotel-carousel--block.tpl.php' -->`

This way you will discover the cause and learn something new about your Drupal project.

Remeber to clear cache (at least theme registry cache) after each change connected with template files. This assures that your theme "knows" about *tpl* file. The same applies to preprocess or hook functions.

Remove `mytheme_preprocess_views_view` \- try to solve initial problem first.

---
Tags: 7, views, theming
---


# Question
Title: Automatically fill in the subject line of contact form
Is there a way to automatically fill in fields in Drupal 8 Contact forms, for example by passing the value in the URL? E.g.

/contact/myform?subject=Subject%20line

If Drupal doesn't have this built-in, does anyone know of a javascript plugin that will do this?

# Answer
There isn't a built-in way to do this with the contact entity form. The prepopulate module looks like it would be covered under this scenario, but it doesn't work on contact forms.

As an alternative, a simple form alter with a custom module could do this on the back end, or front end, with a `hook_form_alter()` invocation.

The backend solution could alter the default form value:

```
function MYMODULE_form_alter(&$form, $form_state, $form_id) {
  // Set the default subject based off the subject query param.
  $default_subject = \Drupal::request()->query->get('subject');
  $form['subject']['widget'][0]['value']['#default_value'] = $default_subject;
}

```

Or the frontend solution can attach a custom JS file:

```
function MYMODULE_form_alter(&$form, $form_state, $form_id) {
  // Assuming mymodule has defined a drupal.mymodule library
  // within mymodule.libraries.yml
  $form['#attached']['library'][] = 'mymodule/drupal.mymodule';
}

```

Then have the attached JS attach to a Drupal behavior:

```
(function ($, Drupal, drupalSettings) {

  // Attach a drupal behavior that uses jQuery to alter the form value.
  Drupal.behaviors.mymodule = {
    attach: function () {
      var subject = '';
      // @TODO: parse location.search for the subject query param.
      $('#edit-subject-0-value').val(subject);
    }
  };

})(jQuery, Drupal, drupalSettings);

```
> 2 votes

---
Tags: 8, emails
---


# Question
Title: How do I show a Drupal 8 contact form on a page?
I've created a new content type called "Form Page", with a required field being a reference to a contact form. So on the page you would have a body, and under that the contact form itself. I can't seem to figure out how to display the form on the page. I either get a link, or the system name of the contact form printed out. How would I go about this?

# Answer
> 3 votes
There needs to be a little more to the Contact Form entity for you to be able to display it. The easiest way to get this is to install the Contact Storage module. After doing this, your manage display options will include "Rendered entity" which will give you the contact form as you hoped and expected!

---
Tags: entities, emails
---


# Question
Title: Views remove link to content based on publication status
Drupal 8. I have a list of images that link back to a content page. If the page is unpublished I want to remove the link.

So far I've set up a `hook_post_render` that checks the publication status. The only way I can think to move forward is to make make the view put out a link as a separate field, then conditionally remove the value. I don't love it and I'd rather jump in to where views is wrapping the image.

# Answer
> 0 votes
With Views's support for Twig, you can now implement conditional hyperlinking without any hook modification to your view.

1. Add a *Content: Path* field to your view with **Exclude from display** checked.
2. Add a *Content: Publishing status* field to your view with **Exclude from display** checked, using the *True/False* **Output format**.
3. Add a *Image (field\_my\_image\_field:target\_id)* relationship to your view that targets your specific image.
4. Add a *File: URI* field to your view with the **Exclude from display** checked, using the *File URI* as the **Formatter**, and the **Display the file download URI** checked.
5. Finally, add a *Global: Custom* field with custom Twig that can check the publishing status value for displaying the link and use the excluded fields as replacement patterns.

For example:

```
{% if status == 'True' %}
<a href="{{path}}">
  <img src="{{uri}}" />
</a>
{% else %}
  <img src="{{uri}}" />
{% endif %}

```

---
Tags: views, theming, hooks
---


# Question
Title: Pre-Populate Dropdown in WebForm from link
I have a Drupal 7 webform with a dropdown list of Products \- Product A \- Product B \- Product C \- etc...

I want to place a button link on another page "How to Buy Product A" that will bring up the webform with Product A selected in the dropdown.

The Field Key in the Webform for the dropdown is: railing\_system\_model

Do I just add something to the link URL??

I have no idea where to begin, is there a module that will do this?

Regards,

John

# Answer
hook\_form\_alter() or hook\_form\_form\_id\_alter() is what you're looking for here.

First your link how ever it's constructed should have a query parameter kind of like "/webformurl?product=a". This would be a link back to your webform.

In one of the hook form alters, you'd check for the value in the url if it doesn't exist do nothing. If it does change the default value for the form field.

If you're not sure how to alter the field on your form maybe check out this link for additional details - Programmatically modifying a webform with hook\_form\_alter()
> 1 votes

# Answer
The Prepopulate module will let you pre-set most form values by adding a parameter to the URL corresponding with the field name. You'd use something like this (inspect your generated form for the proper variable name to use, and watch you are using the proper underlines/dashes):

http://www.example.com/node/add/blog?edit\[railing-system-model\]=your\_key
> 0 votes

---
Tags: webforms
---


# Question
Title: How do I link menu to certain section in one page theme?
How do I link menu to certain section in one page theme?

What is the path should I add if "about" menu link to "about" section?

>

The single page is combination of different blocks.

# Answer
> 1 votes
You can do this by giving `path` of your menu to `id of that block`. **BUT** there is a problem, Default Menu path in Drupal will show you invalid entry as ID of the block are not real path so it is not allowed.

To solve this Void Menu module comes in picture,

Follow following steps:

1. Download and enable the Void menu module.
2. Get your block-id by inspecting the HTML.
>
3. Go to Modules/Void menu/Configuration, in the section of `<void1>` save the Id of that block e.g. I have a `id="block-block-4"`, so I will paste `#block-block-4` and save it.

>
4. Go to Structures/Menus/Your menu/About link, In the path just paste `<void1>`, save it.

>
5. Now, you are good to go, when you will click that about menu link it will scroll you down to that block on same page.

*Note: In Drupal-8, You do not have to do anything, just save the Id in path, and that's it. This feature is provided by default in Drupal-8.*

---

# JQUERY Effect

Till above procedure it is just fine, you can go ahead with that. **BUT** if you want the Smooth JQUERY effect like whatever is provided in your example website.

Just download Scroll to destination anchors, enabled it, That's it. Now it will Scroll down with smooth Jquery Effect.

---
Tags: 7, navigation
---


title: Embed and display PDF viewer

text:
# Question
Title: Embed and display PDF viewer
I'm looking for a solution to display some of my PDF files with a viewer.

I found many solutions for Drupal 7 but not yet for Drupal 8.

Is there any module or open source solution to display PDFs in a Viewer ?

# Answer
You can use the Embedded Google Docs Viewer module for that

> **Drupal 8**
>
> This module provides a formatter for the File field type. This formatter presents the file as a fully rendered object within a web page - i.e. it displays the contents of the file as appropriate to its filetype (Adobe Acrobat **.pdf**, Microsoft Word .doc/.docx, Microsoft Excel .xls/.xlsx, Microsoft Powerpoint .ppt/.pptx), using the Google Docs embedded rendering engine.

There are some other modules but those are in Dev version. Have a look at the Comparison of PDF viewer modules
> 2 votes

---
Tags: 8, files
---


title: Dynamic weight for Blocks

text:
# Question
Title: Dynamic weight for Blocks
I want to change the block weight in sidebar for each page request, So the blocks position would be change for each request.

Is there any way to do it ?

# Answer
> 1 votes
Drupal 8 is providing a hook to alter the region template\_preprocess\_region, it would prepares values to the theme\_region.Adding the following codes in THEMENAME.theme file would solve the problems,

```
function themename_preprocess_region(&$variables) {
  if ($variables['region'] == 'sidebar_second') {
    $variables['elements'] = shuffle_assoc($variables['elements']);
    $content = '';
    foreach ($variables['elements'] as $key => $value) {
      if (is_array($variables['elements'][$key])) {
        $content .= \Drupal::service ('renderer')->render($value);
      }
    }
    $variables['content'] = array(
      '#markup' => $content,
    );
  }
}

function shuffle_assoc($list) {
  if (!is_array($list)) {
    return $list;
  }

  $keys = array_keys($list);
  shuffle($keys);
  $random = array();
  foreach ($keys as $key) {
    $random[$key] = $list[$key];
  }
  return $random;
}

```

For more details, check here

# Answer
> 0 votes
For Drupal 7, you could use something like hook\_block\_list\_alter to alter the blocks on the page. Keep in mind that you might also want to use something like that to make this work.

Alternatively, something for Drupal 8 too, you can create a (block) view that contains whatever you're displaying in these blocks in a single block and then just sort them randonly.

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


# Question
Title: Boost – Cache expiration does not clear cache in views pages
When a node is edited and saved the Cache expiration module should clear the cache on that node, which it does. However if that same node is used in a View, I have discovered that the old content still shows. Unfortunately 90% of the main content is shown using Views.

So in the cache expiration configuration page I have ticked the "Custom pages" option and entered `products|wildcard`, because all sub pages after products/ contains views that need to be cleared. But this does not work.

I have tried to use `drush cc views` (success message), which does not work, `drush cc all` does not show the new content either. The only thing that actually works is to go to admin/config/performance and click the `Clear all caches` button.

What is the best way to sort this problem, so that the Cache expiration module also works on Views?

EDITED:

> I haven't found the solution for this problem yet. Any ideas would be really helpful. Anyone? I should probably also mention that I use the Boost module to chache my pages, along with the Cache Expiration module.

# Answer
Finally the solution was simple. Apparently you cannot use aliases in the Custom pages settings in the Cache expiration module. By adding `taxonomy/terms|wildcard` in the custom pages box, and also setting the cache to `None` in each concerned View (in the Advanced section), the cache expiration worked as wanted.

Hope this helps, if anyone else has this problem.
> 0 votes

---
Tags: 7, caching
---


# Question
Title: How to split content for different target audience?
We're having a bit of a difficulty finding the best way to solve the current issue: it's a multi-site and multi-lingual set-up for a customer that is active in different countries. For each country a separate database is uses (multi-site) and each country has an English + local language variation (multi-lingual).

The customer also has a split audience (private vs. business) and all pages have a one-to-one match, meaning if you are on a `/en/private/foo` page, you could go to `/en/business/foo` just by switching the target audience (same way the language switcher works).

The problem is you'll have two switcher blocks on the page that have to be in sync:

* language (english/local language)
* audience (private/business)

How would you split the content and keep the relation between the different nodes for different audience groups? This also has impact on other Drupal components, the menu for example.

We've been looking at two different approaches:

* separation on content level (taxonomy or field to select the audience group)
* grouping the content (e.g. `og` module, or the new kid on the block `group`)

Any people out there that had the same issue and how did you solve it?

# Answer
@max I am assuming that since there is a 1-1 relation between 'private' and 'business' content, you are probably just hiding (restricting) content in on of the two. So if for example, your 'private' content is only available to authenticated users, or user who paid for the content, then essentially the other (business) content is a reduced version (teaser)?

If that is the case, then maybe you can consider using different display modes for the same node - in other words, you only have one node for both business and private, but with different view modes. The one with restricted access (lets assume that is business) will show nodes using the 'teaser' view, while the other will render the node using the 'full' display mode.

It should be easy enough to change the display mode dynamically on load / render based on the user's status (logged in, paid for content, etc).

The other option, and you could even combine this, is to use content access modules, specifically field level access, to automatically control which fields will be rendered or not. So in this configuration, you could always render the node using the same (possibly different) display modes, but based on the authentication level of the user, simply do not show the field: I can confirm that I have personally used this and it does work (http://www.startnetwork.org).

All things being equal, I would personally only have one node (as opposed to 2 implicitly related nodes) and then simply control what information (or how much) is shown.

If you have any questions - please let me know: happy to help.
> 2 votes

# Answer
I would use the Group module to create a group for each country, and combine that with using the subgroup sub-module to implement 4 subgroups for each country:

* Business - English language.
* Private - English language.
* Business - Local language.
* Private - Local language.

That will give you already a solution that works for D8, with all the flexibility you need to organise (split) your content based on your target audience.

Since the Group module is fully entity based, you can take advantage of any type of typical functionality offered by modules such as the Views module.

And for anything that requires custom code, you have various hooks available (refer to the Development Guide for some more details on that).
> 0 votes

---
Tags: 8, i18n-l10n, multi-sites
---