# Question
Title: How to customise calendar week view's day title?
For example, how can I show `Jul 4 (Mon)` instead of the default `Mon` as day title?

# Answer
> 2 votes
Y rectify like this and that seems good for me:

```
function template_preprocess_calendar_week(&$vars) {
$min_date = clone $vars['view']->date_info->min_date;
foreach ($vars['day_names'] as &$cell) {
 $cell['date'] = $min_date->format('j');
 $cell['data'] = $cell['data'] . ", " . $cell['date'];
 $min_date = $min_date->modify('+1 day');
}
}

```

# Answer
> 1 votes
You need to add your own theme template for your calendar month display.

Within the Views UI under the **Advanced \> Theme: Information** link you'll find a link to display the template for **calendar-month.tpl.php**. You can copy the template over to your theme's template directory. After flush the cache, you can start using that copy as your own custom calendar month template.

Within the template you can see where the header is added via iteration over the `$day_names` variable.

```
<div class="calendar-calendar"><div class="month-view">
<table class="full">
  <thead>
    <tr>
      <?php foreach ($day_names as $id => $cell): ?>
        <th class="<?php print $cell['class']; ?>" id="<?php print $cell['header_id'] ?>">
          !!!<?php print $cell['data']; ?>
        </th>
      <?php endforeach; ?>

```

You can alter it accordingly.

Alternatively, if you prefer to just alter the templates variables. You can add your own theme function for `template_preprocess_calendar_month()` in your theme's **template.php**. For example:

```
function mytheme_preprocess_calendar_month(&$vars) {
  // @TODO: Alter $vars['day_names'] to adjust day headers
}

```

# Answer
> 1 votes
Thanks to Shawn Conn's tips, here is how I modify the `$day_names`:

```
function template_preprocess_calendar_week(&$vars) {

  ...

  $min_date = clone $vars['view']->date_info->min_date;
  foreach ($day_names as &$cell) {
    $cell['date'] = $min_date->format('M j');
    $cell['data'] = $cell['data'] . ", " . $cell['date'];
    $min_date = $min_date->modify('+1 day');
  }

  ...
}

```

---
Tags: 7, views, datetime
---


# Question
Title: hook_theme_suggestions_page() provide default template file inside module folder
I am using hook\_theme\_suggestions\_HOOK() to implement a custom template file in my drupal 8 website like below.

```
/**
 * Implements hook_theme_suggestions_HOOK().
 */
function mymodule_theme_suggestions_page(array $variables) {
  $template_suggestions = array();
  // This is used to display only $content.
  if (isset($_GET['ajax']) && $_GET['ajax'] == 1) {
    $template_suggestions[] = 'page__ajax';
  }
  return $template_suggestions;
}

```

Above code is working fine and I can add template page--ajax.html.twig inside my current active theme and changes in template is reflecting in page.

But when I put that file inside my module itself file is not detecting and changes not reflecting in page and taking default page.html.twg template file.

How can I provide default template file within my module itself?

# Answer
> 3 votes
This issue got resolved by adding `hook_theme()`. Normally theme suggestion templates are only picked up when they are in themes. So We need explicitly define theme suggestions using `hook_theme()` inside a module. Then only it takes templeate from your modules templates folder.

```
/**
 * Implements hook_theme().
 */
function mymodule_theme() {
  return array(
    'page__ajax' => array(
      'render element' => 'elements',
      'base hook' => 'page',
    ),
  );
}

```

---
Tags: theming, 8
---


# Question
Title: How to create a Node Info Bar (or Node Info Block)?
I want to create a teaser with 3 sections:

1. **Title Section.**
2. **Information Section (Info Bar):**

1. When this Node Writed? (Date & Time).
    2. Whom is writed this Node: (Author of Node).
    3. What category consist this: (taxonamy or category).
    4. How Many Viewed (Node View Statistics).
    5. How many add Comment (Comment Statistics).
3. **Show only "Read more" Linke:** at the bottom of a node teaser and remove or unset other links like the "Add New Comment", "2 New Comments", "2 Comments" at the end of a node teaser, because I dont think it makes good sense for people to comment on something that they haven't read yet.

I want to achieve something like the following picture:

# Answer
Okey, you wanted a parallel full stack solution, here it is:

You create a new content type:

You should hide the "view count" field from the form display:

Here is the display for teaser:

You need to do some node preprocess in your custom theme (test.theme):

```
function test_preprocess_node(&$variables) {
  if ($variables['node']->bundle() == 'my_bounty_content' && $variables['teaser']) {
    _test_preprocess_my_content_teaser($variables);
  }
}

function _test_preprocess_my_content_teaser(&$variables) {
  $variables['content']['field_category'] = $variables['elements']['field_category']['0']['#title'];
  $variables['content']['field_view_count'] = $variables['elements']['field_view_count']['0']['#markup'];
  $comment_count = $variables['node']->get('field_comments')->comment_count;
  $variables['content']['comments_count'] = $comment_count ? $comment_count : 0;
}

```

You also need the functionality to increase the node view stats by each visit. Put this code into your custom module '.module' file:

```
/**
 * Implements hook_entity_view().
 */
function base_entity_view(array &$build, \Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode) {
  if ($entity->getEntityTypeId() == 'node' && $entity->bundle() == 'my_bounty_content' && $view_mode == 'full') {
    $view_count = (int) $entity->get('field_view_count')->getString();
    $entity->set('field_view_count', ++$view_count);
    $entity->save();
  }
}

```

And finally create a new template file for your content teaser in your custom theme directory under 'templates' directory:

node--my-bounty-content--teaser.html.twig

```
<article>
    <h2>
        {{ label }}
    </h2>
    <ul class="meta">
        <li>{{ author_name }}</li>
        <li>{{ date }}</li>
        <li>{{ content.field_category }}</li>
        <li>Viewed: {{ content.field_view_count }}</li>
        <li>Comments: {{ content.comments_count }}</li>
    </ul>
    <div>{{ content.body }}</div>
    <a href="{{ url }}">{{ 'Read more'|trans  }}</a>

</article>

```

After this, you only need to list your nodes with teaser view. STILL the views module is the best solution for this, I didn't wrote custom code for this. If you need, let me know I will both post hardcore, and views example for that.

Adding custom theme, library, css is NOT included here.

Remember to clear cache between testing new hooks, templates and so on.
> 1 votes

# Answer
**Views** module covers pretty much everything you want. You only have have to solve "node views count" somehow (extra field, hidden from display).
> 4 votes

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


# Question
Title: Displaying Content Flagged by User Name with Flag Module
I'm using Drupal 7.38 with the Flag (v7.x-3.6) module, along with Views. I'm setting up a flag for content.

My goal is to display a list of users whom are flagging content (along with aggregated count of number of items flagged). With the desired ULTIMATE goal of being able to click on the user's NAME (not UID!) and seeing all the content that the selected user has flagged.

After much research and advice, I was able to eventually accomplish this! The solution was that I had to set up 2 views:

* one being a **content view**.
* and the other one being a **user view**.

Some more details about these views:

* Each of these views with properly configured relationships and contextual filters).
* Only after using 'Rewrite Results' field on the user view (shown below). - Redirecting the output field as a link to the path created by the content view displaying the correctly associated users flagged content.

Here is a screenprint of the 'Rewrite Results' in my User view:

MISSION ACCOMPLISHED, so I thought ...

However, this is all fine and dandy with **1 problem**: when landing into the URL which contains a nice display of the content flagged by the user that was just clicked, I have no way (or 'know' of no way) to successfully migrate the user name into the header of this new page! Labeling & confirming the content now in front of them. So after clicking on a user name with flagged count of content, you land on a nice page of content, but it's unlabeled!

I need to somehow pass, to the new page, the UID (not logged-in!) of the user that was just selected by clicking on the user's name. I cannot figure out how to do.

I tried using the Token Filter module to place the variable into a custom block heading the new page, but it did not work (Token Type not supported).

Any help, hints or suggestions would be highly appreciated!

# Answer
I had the same issue where I wanted to show the title of the content flagged with a certain flag by each user. I solved it as follows:

1. Created 2 views - 1 of users and another of content
2. In the user view, add 'Flags: User's flaggings' relationship (*Refer attachment user\_view*)
3. In the content view, add 'Flags: Node flag' relationship and 'Flags: User uid' contextual filter (*Refer attachment content\_view*)
4. Select 'Display contents of "No results found"' for 'WHEN THE FILTER VALUE IS NOT IN THE URL' in the contextual filter added in step 3
5. Set the format of the content view as 'Unformatted list' and uncheck 'Create a label' option for the 'Content: Title' field
6. Install Views Field View module
7. Embedd the content view inside the user view as a field by passing uid as a contextual filter to the content view

Hope this helps someone.

Regards,

Supriya Rajgopal
> 0 votes

---
Tags: 7, views, flags
---


# Question
Title: Filling an Entity Reference programatically
I am creating a node programatically and one of the fields in the node is an entity reference field referencing a user.

I am using the guide from https://www.drupal.org/node/1388922 and the general consensus i gather is that I need to do something like;

```
$node->field_customer_nid[$node->language][] = array(
'target_id' => $form_state['values']['entity id'],
'target_type' => 'node',

```

);

My question is where do i pass the values for the target entity(basically the uid)in that array. Is it the target\_id or the entity\_id because my attempts with either of those is not working.

# Answer
The better approach is using entity metadata wrapper.

Below snippet is copied from drupal.org documentation

```
$containing_node = node_load($nid);
$w_containing_node = entity_metadata_wrapper('node', $containing_node);

$nids_to_set = array(42, 23);
$w_containing_node->field_entity_reference_field->set($nids_to_set);

```
> 0 votes

# Answer
You have to specify the entity id and the entity type. The example is referencing a node but you want to reference a user.

Try this:

```
$node->field_customer_nid[$node->language][] = array(
  'target_id' => $entity_id,
);

```

$entity\_id should hold the referenced entity id.
> 0 votes

---
Tags: 7, nodes, entities
---


# Question
Title: How can I add meta tags for pages created with views in Drupal 8?
I need to add meta tags for pages created using views in Drupal 8, I tried to use Metatag module. but it seems like there is no views integration on D8 version of this module. I also tried to install Meta tags Quick but it's not working!

is there any other alternatives? please advice.

Edit: I've already seen the answers for this previous question but all of them are recommending using the modules that I've already tried: *Metatag* currently doesn't support adding meta tags to pages created with views, and *Meta tags quick* doesn't work with current Drupal version 8.0.5

# Answer
> 1 votes
I think that this is still in development, one option is to configure the View as a block, then insert that block on a Page. This won't work for all scenarios, but is a (poor) alternative.

---
Tags: views, 8, meta-tags
---


# Question
Title: How do I define a custom html.html.twig file?
I need to define custom html.html.twig file for particular url. What I did is given below:

```
/**
 * Implements hook_theme().
 */
function mymodule_theme() {
  return array(
    'html__ajax' => array(
      'render element' => 'elements',
    ),
  );
}
/**
 * Implements hook_theme_suggestions_HOOK().
 */
function mymodule_theme_suggestions_html(array $variables) {
  $template_suggestions = array();
  // This is used to display only ajax $content.
  if (isset($_GET['ajax']) && $_GET['ajax'] == 1) {
    $template_suggestions[] = 'html__ajax';
  }
  return $template_suggestions;
}

```

I have copy pasted html.html.twig file from my theme and put it inside my module's template folder and renamed it as html--ajax.html.twig. Changes are reflecting fine but not all default variables are not available in my custom html.html.twig file.

When I open the page I can see the content till `Skip to main content` link. Please help me what I am missing while declaring custom template file.

# Answer
> 3 votes
If you want to return 'render element' this would be 'html':

```
'render element' => 'html',

```

But you probably don't need this, better return the base hook so that drupal fetches the variables from the hook `html`:

```
function mymodule_theme() {
  return array(
    'html__ajax' => array(
      'base hook' => 'html',
    ),
  );
}

```

---
Tags: theming, 8
---


# Question
Title: Form in custom template does not submit data
I have a custom form which I render in a custom template. I render the elements separately but the submit button does not fire the data to the validation/submit function. When I render the whole form at once it works fine.

**This does not work:**

```
$form = drupal_get_form('my_module_form');
print render($form['title'];
print render($form['submit'];
print drupal_render_children($form);

```

**This works:**

```
$form = drupal_get_form('my_module_form');
print render($form);

```

**This also works:**

```
$form = drupal_get_form('my_module_form');
print render($form['title']);
print render($form);

```

So apparently I'm missing something but can't find what. Can somebody give me a hint what I'm doing wrong?

# Answer
Check the html your template outputs - I am pretty sure it is missing the `<form>` tag around your fields - without that element your form wont submit however as it contains necessary data (post methode and action to name two).

`drupal_get_form()` retrieves the entire render array for a functional form, but you only pick two form elements to print to screen. It does display the elements because they are themselves valid render arrays, but the functionality of the form is lost that way.

If you really want to ommit fields in the template try to unset the fields you do not want to display. E.g. `unset($form['field_to_hide'])`. This leave the render array of the form intact.

---

That said, hidding fields is commonly done in a preprocess function and not in the template itself. Since it is a custom form you can do it directly in your form declaration.

```
$form['field_to_hide']['#access'] = 0;
$form['field_to_hide']['und']['#disabled'] = TRUE;

```

You can use this approach to set custom data you want to save with the form and the user isn't supposed to see. It's basically a hidden field.

---

If you just want to seperate the fields to add additional wrapper elements or classes you can do that in the form as well:

```
$form['your_field'] = array(
  //[...]
  '#prefix' => '<div class="some-wrapper-class">',
  '#suffix' => '</div>',
  '#attributes ' => array('class' => array('element-class'));
);

```

Check the Form API page to see for which element the two options are available for: FAPI
> 2 votes

# Answer
Please try to call "print drupal\_render\_children($form);" at the bottom of your template file. It may help.
> 0 votes

---
Tags: 7, theming, forms
---


# Question
Title: How to show one node from particular content type into all other pages?
I have content type and have few fields and I want to display each node from that content type into basic page.

In this i want to choose which node i want to display on which page. Like i want to show node1 from A content type into Basic Page 1. and node2 from A into basic page 2.

Any idea?

# Answer
You can use Entity Reference Module

> A generic entity reference field Four widgets: Two implemented on top of the Options module (Select and Radios/Checkboxes), Two autocomplete widgets (one with one text field per entry, one tag-style with comma-separated entries in the same text field) Two formatters: A "Label" formatter, with optional link that displays the label of the referenced entity (the node title, the user name, etc.) A "Rendered entity" formatter, that renders the references entity using a configurable view mode
> 1 votes

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


# Question
Title: Why is an empty field on translated taxonomy term showing default language value?
I have a list of translated taxonomy terms (title, description, link, image). Only some of the translated terms have a value in the link field. Set up as Entity translation

My view pulls all fields and displays the default language link when no value is present on the translated term. I actually do not want to see the default link. I'd like that field to remain empty if it does not exist on the translated term.

I've deselected language fall back in the language config and set the view to hide the field if empty, but I am still showing the default language field value.

Any suggestions?

# Answer
> 0 votes
You may get it to work by using the Internationalizations Views module, which extends the i18n module with multilingual support for Views.

To make Views results correspond to the language switcher, add a filter for **Content Translation: User's Current Language**, which is the language that an authenticated user has set in the user settings (it is NOT the same as the current browser language or the site language).

If no option for the **User's Current Language** is available in the filter criteria form, then verify your configuration at *Configuration -\> Languages -\> detection and selection*: The order should be **URL, Default, User** and not something like **Default, URL, User** (as mentioned also in https://www.drupal.org/node/1701854#comment-6279474).

**Note**: True, the Internationalizations Views module only has a **DEV** / **Alfa** version for D7, but right now there are over 37K users using this version. Therefor I think "DEV" is not a valid release qualifier for that version anymore, because *+37K users can't be wrong*, right?

---
Tags: views, entities, i18n-l10n
---


# Question
Title: Call to undefined function drupal_execute()
In a drupal8 module install file I have used `drupal_execute()` function like as follows

```
drupal_execute("content_copy_import_form", $form_state)

```

But this resulted in an error

> Call to undefined function drupal\_execute().

Any solution?

# Answer
`drupal_execute` hasn't existed since Drupal 6.

In Drupal 8 you can submit a form programatically like this augmented example from `ProgrammaticTest::submitForm`:

```
$values = ['foo' => 'bar'];

// Programmatically submit the given values.
$form_state = (new FormState())->setValues($values);
\Drupal::formBuilder()->submitForm('\Drupal\form_test\Form\FormTestProgrammaticForm', $form_state);

```
> 4 votes

---
Tags: 8
---


# Question
Title: How to change the user-facing label for a Commerce payment option?
I'm using Commerce Braintree as a payment method, which accepts both credit cards and PayPal. Currently it looks like this, which some users are getting confused by since it's not clear that the PayPal button is an *alternative* to the credit card info options:

I'm getting worrying confused customer comments like "But I don't have a PayPal credit card number", so I'd like to edit this label so that it informs the users that they are being presented with two options (PayPal *or* credit card), but I can't find any way to:

How do I this be done?

# Answer
I wasn't expecting something so basic to require an entire extra module, but apparently it does:

* Download and install Commerce Payment Alter
* Set new labels at the admin page admin/commerce/config/payment-methods/alter

Don't forget to document for administrators that they need to go to a whole different page if they want to rename a payment method's user facing label.
> 1 votes

---
Tags: commerce
---


# Question
Title: How to return node object on programatically node creation
I can create node programmatically with following snippet

```
 use \Drupal\node\Entity\Node;

// Create node object with attached file.
$node = Node::create([
  'type'        => 'article',
  'title'       => 'Druplicon test',

])->save();

```

but it only returned "1" on successful,I want to return the created node object . how can I achieve that?

# Answer
It's `Entity::save()` that returns the integer, so:

```
$node = Node::create([
  'type'        => 'article',
  'title'       => 'Druplicon test',
]);

$node->save();

return $node;

```
> 8 votes

---
Tags: 8, nodes
---


# Question
Title: How to inject configuration values into services?
In Symfony 2 when defining a service it is possible to inject configuration parameters by referencing them with `%parameter.name%` strings. For example:

```
services:
  app.mailer:
    class:        AppBundle\Mailer
    arguments:    ['%app.mailer.transport%']

```

But what is the correct Drupal 8 approach to injecting configuration values into services? Of course I don't want to use `\Drupal::config()` inside a service class. Passing configuration values each time a service is referenced does not make much sense either.

I know that I can inject the config service itself and then get configuration values from it, but that looks a bit crappy as my service itself has know how to read data from configuration service. For example:

```
# Yaml service configuration
services:
  app.mailer:
    class:        mail_module\Mailer
    arguments:    ['@config.factory']

```

PHP

```
<?php
class Mailer {
  public function __construct($config) {
    $this->mailTransport = $config->get('mail.config')->get('transport');
  }
}

```

Is there any other way to do this?

# Answer
> 8 votes
You can use a factory for your `app.mailer` service. The factory take cares of retrieving the configuration for the service. The service can stay decoupled from the configuration service and does not need to know how the config parameters are named.

```
services:
  app.mailer:
    class:       Drupal/mail_module/Mailer
    factory:      Drupal/mail_module/MailerFactory:create
    arguments:    ['@config.factory']

class MailerFactory {
  static function create($config) {
    return new Mailer($config->get('mail.config')->get('transport'));
  }
}

class Mailer {
  public function __construct($transport) {
    $this->mailTransport = $transport;
  }
}

```

# Answer
> 3 votes
That's the way to do it. Configuration can change at runtime, the service definition is usually persisted and rebulding it is expensive. Assuming it is configuration that you want users to change.

If it is not, then you can use parameters, just like the symfony example. Then you can put your configuration in services.yml in sites/default. But you can only change it by changing the code and rebuilding the container.

# Answer
> 3 votes
You can use a factory or configurator service that is aware of how the config factory works etc, that keeps your service decoupled from the config factory. The HTTP client in core has a configurator if you need an example. See https://symfony.com/doc/current/service\_container/configurators.html#using-the-configurator for docs.

---
Tags: 8
---


title: Problem with SSL certificate

text:
# Question
Title: Problem with SSL certificate
I just enable SSL certificate for my domain. I added that in my .htaccess file:

```
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^domainname\.com*
RewriteRule ^(.*)$ https://www.domainname.com/$1 [L,R=301]

```

And:

```
# HSTS.
<IfModule mod_headers.c>
  Header always set Strict-Transport-Security "max-age=15768000; includeSubDomains; preload"
</IfModule>

# Cookie secure.
<IfModule mod_headers.c>
  Header set Set-Cookie HttpOnly;Secure
</IfModule>

```

And I changed the line in my settings.php file:

```
$base_url = 'https://www.domainename.com';

```

And :

```
$conf['https'] = FALSE;

```

All my https site displays well with the little green padlock, but the following errors appear in the dashboard drupal :

The Piwik module displays the following error:

> Message d'erreur The validation of "https://analytics.s1biose.com/piwik.php" failed with error "Error opening socket ssl://analytics.s1biose.com:443" (HTTP code 0).

# Answer
> 2 votes
There are some known issues with Drupal 7.x in some server configurations particularly around PHP 5.6 and OpenSSL 0.9x due to changes in how PHP verifies SSL certificates. Acquia has some notes about the cause and options (including a core patch to try to address some instances of the problem but read the whole article before considering that option).

On shared hosting you'll likely want to try the Alternative HTTP Client module to see if it resolves the notice.

---
Tags: 7, .htaccess, configuration, ssl, http-request
---


# Question
Title: Pass view contextual filter arguments programmatically
I want to pass contextual filter arguments programmatically to a view. I know it can be done through `views_get_view` and `views_embed_view`, but I want to pass it to a view's page display. Also I want to pass multiple arguments to the view, so it won't be good to pass all the arguments in the url. I tried to pass the arguments using `$view->args = implode('+', $args);` in `hook_views_pre_render`, but it didn't work. Does anyone know how to pass contextual filter arguments using any of view hooks?

# Answer
I got the solution. It can be done using hook\_views\_pre\_view(). Since `hook_views_pre_view()` allows altering a view at the very beginning of views processing, before anything is done, I am able to feed the arguments to the view.

```
function MODULE_NAME_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == 'myview' && $display_id == 'page_1') {
    $tids = custom_function();
    $args[] = implode('+', $tids);
  }
}

```

Hope this is useful to someone :)
> 8 votes

---
Tags: 7, views
---


# Question
Title: How to display a views block on pages with a specific combination of URL patterns?
I'm using the Group module (1.0-alpha7) on a Drupal 8.1.5 and I want to display a view of recent article in my groups.

I want to display the view on groups page (`mywebsite/group/x` where x is id of group) but only this pattern of URL. For example when I create an article in a group the URL is : `mywebsite/group/x/node/create/article` and I don't want to show the view on this page.

I'm trying to use Blocks Visibility Groups module module to do it but for the moment I don't find the conditions to make it work.

# Answer
> 1 votes
Using the Block Visibility Groups module, perform these steps:

1. Define a new ***Block Visibility Group***, say you name it "***Group pages***".
2. For this newly created \*Block Visibility Group" (named ***Group pages***"), add 2 ***conditions*** by selecting a condition related to the "Request path", which look like so:

* Return true on the following pages: `group/*`.
    * **Do not** return true on the following pages: `group/*/node/create/article` (not sure if you want the `/article` suffix to be added, pick what fits your content types).
3. If you also want to show the `Global Blocks`, then mark the `Show Global Blocks` as checked.
4. Use the `Place block` button to place the Views block in the theme region of your choice.

**Notes**:

---
Tags: views, 8, blocks, group
---


# Question
Title: What Plugin goes "type" of a FieldStorageConfig type?
I have a module creating a field type. It works. I can create and add the field through the admin UI. However, I am trying to update a content type with hook\_update\_N and change a field from entity reference to my field type. I am creating the FieldConfig and FieldStorageConfig like this

```
$field_storage = FieldStorageConfig::create([
       'field_name' => 'content_category',
       'entity_type' => 'node',
       'type' => 'my_field_type',
    ]);

$field = FieldConfig::create([
      'field_storage' => $field_storage,
      'field_name' => 'content_category',
      'bundle' => 'story',
      'label' => $label,
      'settings' => array('display_summary' => TRUE),
      'entity_type' => 'node',
    ]);
    $field->save();

```

This results in an error that says

```
The "my_field_type" plugin does not exist

```

but i can create a field of type "my\_field\_type" and when I export configurations for my field created through the UI the type says "my\_field\_type"

So What plugin is it looking for in the "type" field of a fieldConfigStorage? In my Plugin folder of my module the Formatter.php Field.php and Widget.php which of these is the correct one?

# Answer
> 0 votes
My Bug was actually in

```
entitity_get_form_display()->setComponent('field', array(
type=>my_field_type))

```

it should have been

```
entitity_get_form_display()->setComponent('field', array(
type=>my_field_type_widget))

```

---
Tags: entities, 8
---


# Question
Title: How to get an array of referenced entity ids from an entity reference field
I have a `entity_reference` field with `BaseFieldDefinition::CARDINALITY_UNLIMITED` cardinality. I want a list of referenced entity ids. I know that I can get all the referenced entities by calling `$x->referencedEntities()`, but I want only the ids to get the entities loaded later. Currently I am doing this:

```
  $a = [];
  foreach ($entity->autoren as $v) {
    $a[] = $v->target_id;
  }
  $this->setCurrentAnwaltReferenzen($a);

```

Does anyone know a better solution like it was in D7 (-\>raw())?

Thanks

# Answer
> 37 votes
As an alternative you can do it in one line with an array function instead of a loop:

```
$ids = array_column($entity->autoren->getValue(), 'target_id');

```

Edit: Use `getValue()` to only get the array of the field.

---
Tags: 8, entities
---


# Question
Title: how do I get the user ID other than the one for the current logged in user?
How do I the user ID of the account profile that an administrator user is currently viewing/editin? I can't use `\Drupal::currentUser()` as it always returns the administrator details.

I tried `\Drupal::routeMatch()->getParameter('node')` and `\Drupal::request()->attributes->get('node')`, but it returns this error:

> Call to a member function id() on null...(file path)

# Answer
Assuming that you're viewing a page at a path like /user/42, then you can use the RouteMatch class. Your example is close, but you need to change the parameter passed to the getParameter() method. The parameter in this case is named 'user' not 'node'. You can determine the parameter name from the route definition. Not all routes have parameters, but when they do, they are specific to the route in question.

In this case the route (entity.user.canonical) is defined by \Drupal\user\Entity\UserRouteProvider::getRoutes. And the 'user' parameter is the UID of the user entity in question. Given that, you can use RouteMatch to get the ID in one of two ways.

Load the $user object specified by the user parameter. Which is probably more common. I'm guessing if you're trying to get the UID it's so you can load the user object. With this method parameters are processed by the parameter conversion system, which does operations such as converting entity ID parameters to fully-loaded entities

```
$user = \Drupal::routeMatch()->getParameter('user');
$uid = $user->id();

```

Or access the parameter value directly:

```
$uid = \Drupal::routeMatch()->getRawParameter('user');

```

This change record provides a bit more information https://www.drupal.org/node/2295317
> 11 votes

# Answer
Replying to @eojthebrave (but I do not yet have enough reputation to comment directly, hence this new comment).

Good answer, helpful, thank you. Exactly what I was looking for.

Just for info to share with others, I discovered that `\Drupal::routeMatch()->getParameter('user')` does not always return a user object. When viewing the main 'view' tab on the user profile it does return an object:

```
$path => /user/1346
$route_name => entity.user.canonical
$user => object
$uid => 1346

```

But if on a contrib-supplied tab, for example provided by a view, you get:

```
$path => /user/1346/scheduled
$route_name => view.scheduler_scheduled_content.user_page
$user => numeric
$uid => 1346

```

In these cases you want to avoid `$uid = $user->id();` which will cause an error. The good news is that in both cases `\Drupal::routeMatch()->getRawParameter('user')` returns the uid as an integer.
> 0 votes

# Answer
If you are talking about in the admin section, as in /user/42 - the user ID is the last fragment of the URL - take a look at drupal\_parse\_url to break your URL into components.

Once you know what the user id is (42 in the case above), you can use user\_load function to load the profile of user 42
> -1 votes

---
Tags: nodes, 8
---


# Question
Title: How do I render an entity view mode like 'teaser' in a twig template?
I have an entity reference field in one content referencing an other content.

What I'm trying to achieve is to display that reference in a teaser format programmatically.

I was hoping that I could do something like this :

```
{{ node.field_entity_ref.view('teaser') }}

```

But that doesn't work. Do I need to declare a preprocess anyway ? If so what's the best practice ?

# Answer
> 11 votes
The best practice would be to configure the reference field in UI as teaser and use it in the node template:

```
{{ content.field_entity_ref }}

```

If this is not an option for your case, you would probably need some code in preprocess.

But much easier is to use the module Twig Tweak, which can render nodes without preprocess:

```
{{ drupal_entity('node', node.field_entity_ref.0.target_id, 'teaser') }}

```

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


# Question
Title: Syntax for referenced variables in hook_commerce_physical_order_weight_alter?
I'm trying to add a fixed weight to all cart order for shipping. I know I need to implement hook\_commerce\_physical\_order\_weight\_alter() but I'm unsure of how to implement the function in a custom module. I have been testing this code in the devel php exectute window

```
global $user;
$order = commerce_cart_order_load($user->uid);
$weight = commerce_physical_order_weight($order, $unit = 'oz');
function commerce_physical_order_weight_alter(&$weight, $order, $unit){
if ($weight['weight'] >0)
{$weight = $weight + 6;}
}
dpm($weight);

```

Where I am confused, is passing the variable by reference. From what I understand, this should be enough to increment the weight but it returns the unadjusted weight

I can grab all of the stuff I need outside the function, but I'm unclear about passing the variable by reference and how to use that syntax for my purpose. I know that this means that the function returns a modified variable. It doesn't look like the function is called since I've tried to put the dpm in a condition inside the \_alter function and it doesn't run.

Thanks the help so far, and I appreciate the earlier answers.

# Answer
If your `hook_commerce_physical_order_weight_alter` is not fired (remove `if` to double check that it's not), check if `commerce_physical_order_weight()` is fired as alter hook is right at the end (so add `dpm()` or `die()` at start of the function):

```
    function commerce_physical_order_weight($order, $unit = 'lb') {
      // ...
      // Allow other modules to alter the weight if necessary.
      drupal_alter('commerce_physical_order_weight', $weight, $order, $unit);

```
* if it is not fired, that means the problem is somewhere else, so check if `commerce_physical` module is **enabled** and **configured** properly and you've the right dependency to it,
* if it is fired, then check that:

+ your module is exactly called `add_shipping_weight`,
    + the module file included (add `hook_init()` or `die()` to check)
    + clear your caches (Drupal caches, memcached/redis if used, etc.), so list of hooks can be updated (it's a common mistake)
> 2 votes

# Answer
The reason why this isn't working is because `$weight` isn't an integer, it's an array (much like price field values are).

Looking around the code, it looks like `$weight` will have 2 array keys:

```
  // Update the weight amount using the multiplier.
  $weight['weight'] *= $multiplier;

  // Update the unit type to the target type.
  $weight['unit'] = $unit;

```

So you need to check if `$weight['weight'] > 0` instead of just `$weight > 0`.
> 0 votes

# Answer
Thanks to everyone for the above comments, it got me really close to what I needed - but like OP had difficulty getting it to behave as expected. In the end, I found that it was actually very simple. By including the following in my custom helper module, I was able to add a weight to the total order:

```
/**
* Implements hook_commerce_physical_order_weight_alter()
*/
function YOUR_MODULE_commerce_physical_order_weight_alter(&$weight, $order, $unit = 'lb') {
    $weight['weight'] = $weight['weight'] + $YOUR_VALUE;
}

```
> 0 votes

---
Tags: commerce, hooks
---


# Question
Title: What is the best way to track unique and overall clicks at my newsletters
I send newsletters from my Drupal-7 website and I want to track how many times the links where clicked and how many unique click events I had.

I use Simplenews module and I use some basic GA utm parameters, but the results I get are not satisfying. What do you suggest I use. Is there a method, or a way to get that? Everywhere I search there is not a valid answer to my question.
Thanks in advance.

# Answer
I would suggest checking out https://support.google.com/analytics/answer/1033867?hl=en as it will help you build a link you can put in your newsletter that when clicked takes the person to whatever page you direct them to, but has analytic code built into the link so that you can track how many and how often it is used. Total sessions and unique users will both be tracked.
> 0 votes

---
Tags: 7, emails, google-analytics
---


title: Where can I view different form modes?

text:
# Question
Title: Where can I view different form modes?
I created a simple content type and a form mode for this content type. Where can I view this form mode after creating it? I see no option for form modes when creating a content type. I would have expected an option to be presented when clicking on "Add Content" to select "Add xy content with xy form mode"? Raised it as an issue here https://www.drupal.org/node/2530086

# Answer
> 0 votes
The answer given in that issue: nowhere.

Currently nothing in core makes use of custom form modes.

# Answer
> 1 votes
You can try these modules.

https://www.drupal.org/project/form\_mode\_control https://www.drupal.org/project/form\_mode\_manager

I prefer form\_mode\_control. Form\_mode\_manager create a view form mode for all content types.

These modules can be restricted with permissions. But I prefer https://www.drupal.org/project/field\_permissions; it is more acurated by field.

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


# Question
Title: How can we display permissions to users?
Is there any way we can display user permissions (e.g. *delete all nodes*) to a user role inside a view?

Permissions would be change-able with check-boxes.

# Answer
To create a view of permissions you'd have to write a custom module that would allow views to do the search. I'm not aware of a module that does that now. Given how roles are defined and managed this would be a challenging module to get right.

If you just want to improve the user interface for permissions form you might look at these modules:

If you want to give admins a limited number of roles they can assign the Role Assign module may provide what you need.
> 3 votes

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


# Question
Title: How to send monthly newsletter if the site is complex and has a lot of content types?
I want to send monthly newsletter to subscribers via Drupal. The website has lots of content types (news, events, books, courses, blog posts etc.). If the site has only one content type it would be easy to prepare this newsletter with Simplenews module or Mailchimp etc.

Because the site is so complex and needed to create some specific views for each content type I wonder if **is it better to prepare custom newsletter manually (without Drupal interface)** or **is there any solution to send newsletter via Drupal interface, "easily" and automatically**?

# Answer
There are a plethora of newsletter generation modules in various states of support. But if you want a first class newsletter that your audience reads you almost certainly want to take the time to write and layout the newsletter in a tool meant for the job (Mailchimp's interface or a competitor).

Newsletter generators are very appealing and can be effective if you have lots of very targeted segmentation of your list. But most of the time if you are sending one news letter to the entire list they are more overhead than value.

Most of the use cases people look to a generator to support are signs of a poor communications strategies. For example: I want to send a daily newsletter about XYZ and don't have the time to write it carefully every day -- does your audience want *get* and read that much auto-generated mail? Or Laying out my message is too hard to get it right every time -- use a better email newsletter tool that does the job better.
> 3 votes

---
Tags: 7, emails
---


title: How do I embed a 2nd level menu block?

text:
# Question
Title: How do I embed a 2nd level menu block?
I need to embed the 2nd level menu that show up in my 2nd level page /maintenance

in the next level page /maintenance/add-task

Drupal does not have this kind of setting, I'm looking a lot in the core files to try to figure out the proper API code to embed, one of my attempts:

```
$block = \Drupal\block\Entity\Block::load('block_modules_menu_second_level');
$variables['menu_second_level'] = \Drupal::entityTypeManager()
  ->getViewBuilder('block')
  ->view($block);

```

That code is for a simple block, or a custom block. How to evoke the drupal core menu level 2?

What am I missing?

# Answer
> 2 votes
Not quite sure, whether I got you right. Here's my guess: Depending on which theme you use, it may be that it is not a problem with the menu template. In my case, the (main) menu was configured to show only one level in the block settings.

I found out by chance, here is how to change it:

1. Go to https://\<yourdrupalpage\>/admin/structure/block
2. on the respective menu block item (e.g. main menu) click *configure*
3. adjust the number of visible menu levels to your needs

that should to the trick

---
Tags: 8
---


# Question
Title: Set value in $form_state['storage'] seems to change before validation
I am sure that I do not understand something fundamental about Drupal's form API but I hope that someone can help me with that:

I want to create some kind of custom CAPTCHA as the CAPTCHA module states that with caching enabled on your project problems could appear and my project really needs caching via the Boost module. The idea was the following in my forms building array:

```
  $number1 = rand(0, 10);
  $number2 = rand(0, 10);
  $form['numbercheck'] = array(
    '#type' => 'numberfield',
    '#title' => 'Please fill in the sum of '. $number1 .' and '. $number2,
    '#required' => TRUE,
  );
  $form_state['storage']['checksum'] = $number1 + $number2;

```

Then in validation I wanted to do the following check:

```
 if($form_state['storage']['checksum'] != $form_state['values']['numbercheck']) {
  form_set_error('numbercheck', 'The sum was not correct');
}

```

But every time I fill in the form the following happens: say the first random number is 1 and the second number is 2 - I fill in the correct value "3" but get an error "The sum was not correct". Using Devel module and dpm()-function to get the values of $form\_state\['storage'\]\['checksum'\] and the single random numbers I realize that this value changed after submitting the form - while viewing the form the value is correctly "3" but when validation starts the value change to let's say 4 because the then newly created numbers in the then newly created form are maybe 1 and 3.

I tried

```
$form_state['rebuild'] = FALSE;

```

in form building function as I thought that the form may be rebuild before validation starts and therefore the random numbers were newly created as well as the $form\_state array may be changed but this did not solve my problem.

I hope that somebody can help me out with that - thank you very much in advance!

Best, Tobias

# Answer
I don't like the cache method as it is quite complicated. If cache method is the only way to do that. I would recommend using Session Cache API.

In this case, exposing the answer to the form and collecting it from `$form_state['input']` would be my choice.

```
function mymodule_custom_form($form, &$form_state) {
  $input = &$form_state['input'];

  $number1 = rand(0, 10);
  $number2 = rand(0, 10);
  $form['numbercheck'] = array(
    '#type' => 'textfield',
    '#title' => 'Please fill in the sum of '. $number1 .' and '. $number2,
    '#required' => TRUE,
  );

  // hidden field is only hidden to user but you still can inspect it
  // from source. So hash function is used to encrypt here.
  $form['checksum'] = array(
    '#type' => 'hidden',
    '#value' => isset($input['checksum']) ? $input['checksum'] : hash('sha256', $number1 + $number2),
  );

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

  return $form;
}

function mymodule_custom_form_validate(&$form, &$form_state) {
  $hash = hash('sha256', $form_state['values']['numbercheck']);

  // compare the hash result.
  if ($form_state['values']['checksum'] != $hash) {
    form_set_error('numbercheck', 'The sum was not correct');
  }
}

```
> 1 votes

# Answer
What about using cache? That way the sum won't change until the user gets it right:

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

    if ($cache = cache_get('num1'.$_SERVER['REMOTE_ADDR'])) { // user remote IP so each IP will have a different sum
        $num1 = $cache->data;
    } else {
        $num1 = rand(0, 10);
        cache_set('num1'.$_SERVER['REMOTE_ADDR'], $num1, 'cache');
    }

    if ($cache = cache_get('num2'.$_SERVER['REMOTE_ADDR'])) {
        $num2 = $cache->data;
    } else {
        $num2 = rand(0, 10);
        cache_set('num2'.$_SERVER['REMOTE_ADDR'], $num2, 'cache');
    }

    $form['numbercheck'] = array(
        '#type' => 'textfield',
        '#title' => 'Please fill in the sum of '. $num1 .' and '. $num2,
        '#required' => TRUE,
    );

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

    return $form;

}

function test_form_validate($form, &$form_state) {

    $num1 = cache_get('num1'.$_SERVER['REMOTE_ADDR'])->data;
    $num2 = cache_get('num2'.$_SERVER['REMOTE_ADDR'])->data;

    if(($num1 + $num2) != $form_state['values']['numbercheck']) {
        form_set_error('numbercheck', 'The sum was not correct');
    }
}

function test_form_submit($form, &$form_state) {

    // Once they get it right clear the cache so next time the sum will be different
    cache_clear_all('num1'.$_SERVER['REMOTE_ADDR'], 'cache');
    cache_clear_all('num2'.$_SERVER['REMOTE_ADDR'], 'cache');

    die('all done');

}

```
> 0 votes

---
Tags: 7, forms
---


# Question
Title: Creating platform based upon git repo keeps failing
Creating a platform based upon a git repo within Aegir keeps failing. I cloned the repo myself and did a drush make, which succeeded, so I'm not sure what is going wrong.

It keeps failing on:

```
/usr/local/bin/drush --backend=2 @platform_platformsbel provision-verify 2>&1

```

Where I get the following:

```
We could not find an applicable site for that command.
Drush could not bootstrap this platform. Please check the platform directory exists and is readable.

```

I checked and provision and the platform directory gets created, the git repo gets cloned, but that is as far as it seems to go. I've read all the documentation and used our dear friend Google, but neither is able to help me out.

My setup:

* Ubuntu Server 15.10 x64
* aegir 3.4 (installed from http://debian.aegirproject.org, but moved home directory from /var/aegir/ to /home/aegir/)
* hostmaster-7.x-3.4 (Drupal 7.42)
* drush 8.0.5

Git repo used: https://github.com/belsander/drupal-profile-test3

Could somebody point me in the right direction, please? Thanks!

Full output from hostmaster:

```
Task starts processing: Verify: platformsbel
-
Returned from hook drush_hosting_task_validate
-
Calling hook drush_hosting_clone_pre_hosting_task
1 s.
Returned from hook drush_hosting_clone_pre_hosting_task
-
Calling hook drush_hosting_git_pre_hosting_task
-
Returned from hook drush_hosting_git_pre_hosting_task
-
Calling hook drush_hosting_migrate_pre_hosting_task
-
Returned from hook drush_hosting_migrate_pre_hosting_task
-
Calling hook drush_hosting_package_pre_hosting_task
-
Returned from hook drush_hosting_package_pre_hosting_task
-
Calling hook drush_hosting_site_pre_hosting_task
-
Returned from hook drush_hosting_site_pre_hosting_task
-
Calling hook drush_hosting_task
-
Backend invoke: /usr/local/bin/drush --backend=2 --root=/home/aegir/platforms/platformsbel --uri= provision-save '@platform_platformsbel' 2>&1
-
/usr/local/bin/drush --backend=2 --root=/home/aegir/platforms/platformsbel --uri= provision-save '@platform_platformsbel' 2>&1
-
Bootstrap to phase 0.
-
Bootstrap to phase 0.
-
Found command: provision-save (commandfile=provision)
-
Loaded alias @server_master from file /home/aegir/.drush/server_master.alias.drushrc.php
-
Loading mysql driver for the db service
-
Loading apache driver for the http service
-
Driver type not specified for the git service, provide it with --git_service_type
-
Driver type not specified for the db service, provide it with --db_service_type
-
Driver type not specified for the http service, provide it with --http_service_type
-
Driver type not specified for the git service, provide it with --git_service_type
-
Calling hook drush_provision_save
-
Loaded alias @platform_platformsbel from file /home/aegir/.drush/platform_platformsbel.alias.drushrc.php
-
Template loaded from Provision Config class Provision_Config_Drushrc_Alias: /usr/share/drush/commands/provision/Provision/Config/Drushrc/provision_drushrc_alias.tpl.php
-
Changed permissions of /home/aegir/.drush/platform_platformsbel.alias.drushrc.php to 640
-
Generated config in write(): Drush configuration file (/home/aegir/.drush/platform_platformsbel.alias.drushrc.php)
-
Changed permissions of /home/aegir/.drush/platform_platformsbel.alias.drushrc.php to 440
-
Returned from hook drush_provision_save
-
Command dispatch complete
1 s.
Scanning into /etc/drush for /.*aliases\.drush(8|)rc\.php$/
-
Scanning into /etc/drush for /platform_platformsbel\.alias\.drush(8|)rc\.php$/
-
Scanning into phar:///usr/local/bin/drush/includes/.. for /.*aliases\.drush(8|)rc\.php$/
-
Scanning into phar:///usr/local/bin/drush/includes/.. for /platform_platformsbel\.alias\.drush(8|)rc\.php$/
-
Scanning into /home/aegir/.drush for /.*aliases\.drush(8|)rc\.php$/
-
Scanning into /home/aegir/.drush for /platform_platformsbel\.alias\.drush(8|)rc\.php$/
-
Scanning into /home/aegir/hostmaster-7.x-3.4/drush for /.*aliases\.drush(8|)rc\.php$/
-
Scanning into /home/aegir/hostmaster-7.x-3.4/drush for /platform_platformsbel\.alias\.drush(8|)rc\.php$/
-
Scanning into /home/aegir/hostmaster-7.x-3.4/sites/all/drush for /.*aliases\.drush(8|)rc\.php$/
-
Scanning into /home/aegir/hostmaster-7.x-3.4/sites/all/drush for /platform_platformsbel\.alias\.drush(8|)rc\.php$/
-
Scanning into /home/aegir/hostmaster-7.x-3.4/sites/aegir.ionica.ca for /.*aliases\.drush(8|)rc\.php$/
-
Scanning into /home/aegir/hostmaster-7.x-3.4/sites/aegir.ionica.ca for /platform_platformsbel\.alias\.drush(8|)rc\.php$/
1 s.
Scanning into /home/aegir/hostmaster-7.x-3.4/sites/default for /.*aliases\.drush(8|)rc\.php$/
-
Scanning into /home/aegir/hostmaster-7.x-3.4/sites/default for /platform_platformsbel\.alias\.drush(8|)rc\.php$/
-
Scanning into /drush for /.*aliases\.drush(8|)rc\.php$/
-
Scanning into /drush for /platform_platformsbel\.alias\.drush(8|)rc\.php$/
-
Scanning into /sites/all/drush for /.*aliases\.drush(8|)rc\.php$/
-
Scanning into /sites/all/drush for /platform_platformsbel\.alias\.drush(8|)rc\.php$/
-
Scanning into /home/aegir/hostmaster-7.x-3.4/../drush for /.*aliases\.drush(8|)rc\.php$/
-
Scanning into /home/aegir/hostmaster-7.x-3.4/../drush for /platform_platformsbel\.alias\.drush(8|)rc\.php$/
-
Loaded alias @platform_platformsbel from file /home/aegir/.drush/platform_platformsbel.alias.drushrc.php
-
Backend invoke: /usr/local/bin/drush --backend=2 @platform_platformsbel provision-verify 2>&1
-
/usr/local/bin/drush --backend=2 @platform_platformsbel provision-verify 2>&1
-
Bootstrap to phase 0.
-
Bootstrap to phase 0.
-
Found command: provision-verify (commandfile=provision)
-
Loaded alias @server_master from file /home/aegir/.drush/server_master.alias.drushrc.php
-
Loading mysql driver for the db service
-
Loading apache driver for the http service
-
Driver type not specified for the git service, provide it with --git_service_type
-
Including /usr/share/drush/commands/provision/platform/backupmigrate/verify.provision.inc
-
Including /usr/share/drush/commands/provision/platform/verify.provision.inc
-
Calling hook drush_provision_drupal_provision_verify_validate
-
Returned from hook drush_provision_drupal_provision_verify_validate
-
Calling hook drush_provision_git_provision_verify_validate
-
Returned from hook drush_provision_git_provision_verify_validate
-
Calling hook drush_provision_drupal_pre_provision_verify
1 s.
We could not find an applicable site for that command.
-
Drush could not bootstrap this platform. Please check the platform directory exists and is readable.
-
Returned from hook drush_provision_drupal_pre_provision_verify
-
Command dispatch complete
1 s.
Returned from hook drush_hosting_task
-
Invoking hosting_verify_task_rollback hooks.
-
Changes made in drush_hosting_task have been rolled back.
-
Command dispatch complete
-
Updated task status to "Failed"

```

# Answer
> 0 votes
Your repository does not contain a Drupal codebase. The current git integration does expect this.

To use your makefile you can use the 'Deploy from makefile' option and point it at a local path or url.

# Answer
> 0 votes
It's a good idea to try it from the command line if it fails from the UI.

In my case, their API was down:

```
colan@snake[Wed 20 17:47]% git clone git@gitlab.com:group/project.git
Cloning into 'project'...
GitLab: API is not accessible
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

```

The other thing to check is that the proper Git modules are enabled at Administration » Hosting » Features.

---
Tags: version-control, aegir
---


# Question
Title: Content Type based template not working for Medical Zymphonies Theme
I downloaded the Medical Zymphonies Theme and has been modifying that to create my own theme.

In the past, I have successfully used content type-specific template files with themes that I created. However, it is not working the current theme. This is the template file for the theme.

I want a template specifically to basic page. So something like page--basic-page.tpl.php.

# Answer
> 0 votes
JamieR has provided a snippets in Drupal.org

```
function themeName_preprocess_page(&$vars, $hook) {
  if (isset($vars['node'])) {
    // If the node type is "blog_madness" the template suggestion will be "page--blog-madness.tpl.php".
    $vars['theme_hook_suggestions'][] = 'page__'. $vars['node']->type;
  }
}

```

---
Tags: theming
---


title: Add Bootstrap into Zen sub-theme

text:
# Question
Title: Add Bootstrap into Zen sub-theme
Right now, I am using Zen theme as basic theme for my website. I want to add Bootstrap into my theme because I don't want to use new theme and setup everything.
Does anyone know if I can only add these two lines of code to setting instead of downloading every single bootstrap file?

`settings[bootstrap_source] = bootstrapcdn
settings[bootstrap_version] = 2.3.2`

I found the above code in someone's theme setting, but I didn't find the meaning of them. So, I am not sure whether this can be worked.

Thank you very much.

# Answer
> 2 votes
> Does anyone know if I can only add these two lines of code to setting instead of downloading every single bootstrap file?

No, you can't do that. That's a setting from, I would guess, the Bootstrap theme itself. It allows you to choose which version of the framework to use for that theme. The Zen theme would have no reason to add Bootstrap, so no reason to use those settings.

Continuing to use Zen as a theme/sub-theme, and replacing its framework with Bootstrap, doesn't sound like a great idea. You'll have problems/headaches upgrading, and plenty of Zen-isms to remove/re-implement to get it to play nicely with the new framework.

Given that all of that work, and more, has already been done for you, setting up a new theme based on Bootstrap is worth re-considering IMO.

# Answer
> 1 votes
They both handle responsiveness in different ways so mixing the two together will probably not produce the results you want.

---
Tags: 7, theming
---


# Question
Title: Why would a field be missing from the Rules data selector?
I've added a couple of fields to the standard product bundle included with Commerce, like so:

I'm now trying to add a rule (*Data Comparison*) based on the "Special Offer Active" field, but for some reason it's missing from the data selector:

The other field I've added ("Special Price") shows up fine.

Anyone know why this might be happening? I've cleared caches a few times and run cron to no avail.

# Answer
I found the answer in the Commerce documentation:

> This is due to the fact that Rules only knows about the default fields that we tell it should function in a manner similar to entity properties. In order to access additional fields, you have to do one of two things in your conditions:
>
> * Use the Entity has field condition to ensure the field you want to access exists on the variable you want to use it for, or
> * Use the Data comparison condition to check the type of the entity (i.e. product type) to gain access to every field on the entity.
> 5 votes

# Answer
Using "Content is of type" condition to show all the available field. Besides, install Conditional Rules to enable inline conditional clause.
> 3 votes

# Answer
For anyone who may have the same problem, "Entity has field" didn't work for me but using the "Entity is of bundle" condition did the trick.
> 1 votes

# Answer
The other thing that is a gotcha (of course) is if the field type does not match the type expected. For example, i was mapping fields from node to another entity type. I had a date field in the entity i was mapping to BUT in rules it was stating it had to be a field of type Text. So i tested and sure enough if i made a text field, then it showed after doing the 'entity is of type bundle'.
> 0 votes

# Answer
i had some fields missing with the 'Entity is of bundle' condition but triggering the rule once (updating a node of given bundle in my case) let the field appear in the list.
> 0 votes

---
Tags: rules
---


# Question
Title: Show the first 4 items in a different format
I have a current view set up that displays a feed of stories and is sorted in descending order. I now need to have the first 4 stories display as a different style then the remaining ones. I have pagination set to 10. I only want the first 4 to show differently on page 1, and then the current style will show on the remaining pages. Is there a way to do this?

# Answer
> 5 votes
You can use views attachment to have a different styles for the first few item in list. By default, the attachment will be displayed in every pages of list.

If you want to limit the attachment works on the first page only, please implement `hook_views_pre_build()` in your custom module.

Assuming views name is `stories`, main display ID is `block_1` and attachment display ID is `attachment_1`.

```
/**
 * Implements hook_views_pre_build().
 */
function mymodule_views_pre_build(&$views) {
  if($views->name == 'stories' && $views->current_display == 'block_1') {

    // if 'page' is not defined, we assume it is the first page.
    if (empty($_GET['page'])) {

      // The offset number y should be equal to the number of items on
      // attachment. If we want to keep the total n items on list, the
      // number of items on main display should be (n - y).
      // Note: get_items_per_page() and get_offset() is not working here.
      $views->set_items_per_page(6);
    }
    else {

      // Remove attachment for other pages.
      $views->is_attachment = TRUE;

      // We don't need to handle the offset anymore.
      $views->set_offset(0);
    }
  }

  // We set the item number again because the it seems
  // be overrided by previous call of set_items_per_page().
  if($views->name == 'stories' && $views->current_display == 'attachment_1') {
    $views->set_items_per_page(4);
  }
}

```

---

# Below is the steps of using views attachment

1. Add attachment display
2. In the attachment display, you need to specify how many items you want to have.
3. Then you need to attach the attachment display to the main display.
4. Remember to set the offset in main display for preventing repeating the item in list.

# Answer
> 1 votes
1. In Views, change FORMAT to Show Fields, if you don't have it already.

2. Add fields, title, body (for formatter you could use Summary or trimmed), post date, comment link, etc...
3. Add image field twice, one with style x other with style y, if you want the top 4 to have different image style.
4. In Fields, Add **View result counter** and start counter at 1.
5. Create a template for your view fields:

**views-view-fields--\[view-name\]--\[machine-name\].tpl.php**

Example: views-view-fields--hello-world--block-1.tpl.php

In template file you add an if statement to test if counter row is 1, 2, 3, or 4

```
<?php

if ($fields["counter"]->raw == (1 or 2 or 3 or 4)){

  echo '<div class="top4-title">' . $fields["title"]->content . '</div>';
  echo '<div class="top4-body">' . $fields["body"]->content . '</div>';
  echo '<div class="top4-image">' . $fields["field_image"]->content . '</div>';
  echo '<div class="top4-date">' . $fields["field_created"]->content . '</div>';
  echo '<div class="top4-clink">' . $fields["comments_link"]->content . '</div>';

} else {

  echo '<div class="reg-title">' . $fields["title"]->content . '</div>';
  echo '<div class="reg-body">' . $fields["body"]->content . '</div>';
  echo '<div class="reg-image">' . $fields["field_image_1"]->content . '</div>';
  echo '<div class="reg-date">' . $fields["field_created"]->content . '</div>';
  echo '<div class="reg-clink">' . $fields["comments_link"]->content . '</div>';

}

```
7. Place template file in your **/sites/all/themes/YOURTHEME/templates** folder
8. **Clear/Flush the cache.**

**Note**: Since the view template gets added to your theme, the view preview will not reflect this template because the view preview uses the administration theme. The default admin theme is Seven. You would have to add the template to Seven too, but IMO that's un-necessary.
9. Go to the page where the view gets displayed to see changes.

---
Tags: 7, views
---


# Question
Title: When do I need a contextual filter vs. a relationship?
Can someone explain the **functional** difference between contextual filters and relationships?

I understand that a relationship is a table join, and a contextual filter is passing parameters to the view. Both adjust view data. **How would you describe when each should be used?**

I have been building complex views for a few months now, but sometimes I still don't have an intuition for what I need - I generally have to find a tutorial on exactly what I am trying to do, and I think it stems from not really understanding these two capabilities.

---

Edit:

Thanks for all the answers helping to describe the SQL building. On that topic, I found this advice very helpful.

# Answer
> 14 votes
Just think of it terms of SQL:

* a 'relationship' is a `JOIN` on another table
* a 'filter' (contextual or not) is a `WHERE` clause.

'Contextual' just means the parameter comes from the current context, e.g. part of the URL, something in the session, etc

# Answer
> 2 votes
I think you described it well yourself. A relationship is a join. You are joining another table to the base table for the view you are creating. A contextual filter is an argument you are passing to the query created by the view.

If you are creating a list of node titles a simplified query you are creating might be:

SELECT title FROM {node};

A contextual filter would pass an argument into that query. You can grab the argument from the URL or a number of other places. In this example the type would be an argument you are passing using a contextual filter:

SELECT title FROM {node} WHERE type = 'page';

An example of a relationship might be accessing user info about the node author. If you added a relationship to the user on the user id the query might look something like this:

SELECT title n, username u FROM {node} n JOIN {user} u ON n.uid = u.uid WHERE type = 'page';

# Answer
> 2 votes
I think some examples can ease understanding.

**When we should use relations**

We have data A and data B, B relates to A. This relation could be caused by Drupal (like author of a node), or be caused by a reference module (like taxonomy, node reference, user reference, etc).

Imagine that A is the content piece and B is the author. We are designing a view of nodes (type A) , and we want to restrict nodes to ones which are written by a user (type B) whose score is more than 100 (imagine this field is added to user fields).

I need data of user. To get these data we use a relation. We make a relationship based on author's uid, which brings information about a user with it.

So we use relationships to access data of B using its relationship to A.

**What is a contextual filter**

Imagine I want a block that lists all nodes written by a user. I want it to be displayed on each user's account page.

I have to filter nodes by something which is contained in the page which the block is shown on. In this situation I use a contextual filter.

I get data from the page (address, title, body, etc) where the block should be displayed; here there is not a straight relation. The view's content must be filtered by the user's id, but we are not getting the uid from a user. Rather, we are getting this info out of the page the view will be rendered on.

So contextual filters are usually used when we want to filter a view based on a place it will be displayed.

# Answer
> 0 votes
Relationships give you information about entities that are not listed in the fields b joining current content with other entities. For example detail information about the author of the node is not in the fields, Only it's `uid` is in there, so by selecting author as relationships you can get the rest of the information.

Contextual filters are similar to regular filters in that you can use mainly the same fields to filter the records on. *Where contextual filters differ greatly is that you do not set the filtering value when you create the View, but it is taken from context. Contextual filters are great for when the View needs to display content dynamically depending on various contextual conditions*

# Answer
> 0 votes
For example, you were tasked to build a Forum that does cross-listing users according to their geolocation.

So, we have a content type called Forum that includes all the necessary fields like entity reference and taxonomy. That entity fields are connected to that forum content type.

**So the way to do it**

We can actually determine the cross-listing the moment the user logged in and choose the right location, and that location we'll use it as a location ID (base on Continent and not base on the Country) That continent will be use as a block (Contextual Filter) to be use as a parameter, once it gets fired or click by the the user, lets say the User chooses "Asia" all that comes out inside the forum will be only "Asia" and i'll place also a exposed filters for the Category \[ Education, Science, Ecosystem, etc.\] and label it as Category above the Forum. So it will be easy for the user to go choose a category they wanted to go or look at to read.

So for the Continent block, i'll use relationship, Adding relationships using the Location Id, not the author id. So, now that location id will be the Identifier, and go back to Contextual Filter and hit "add" choose location id, and the User: Location Id.

Above there is a Relationship that holds the Location id as the identifier. In the forum page, i'll select the "Validator as User" in the "Type of user filter value to allow: select "only allow string usernames".

**SetUp**:

* Setup location Id of the User to use as a Contextual Filter to use as parameter to the forum content type by grabbing or declaring the node to make a bridge that once that geolocation (continent) gets fired it sends us to directly to the forum according by Continent, and the topics within that Continent.
* Forum View, set up all the necessary fields and formats within this View.

I'll use Contextual Filter and Relationship to bind the Content type "Forum" and also the users geolocation id, it helps me determine to filter them accordingly.

As i may not be confident as how this should work, just a quick query. Anyone here would Kindly let me know if i can use the Location id on this matter? Big Thanks.

---
Tags: views
---


# Question
Title: How to add a custom vertical tab to node edit form?
How can I add a block with some HTML to the **Node Add/Edit form**? I've tried adding a new `#markup` field but I couldn't position it where I need by using `weight`.

See image below for desired location: just below the vertical tabs displayed to the right in the Seven theme.

# Answer
If you're looking insert renderable elements into the form array in the same manner as the grouped vertical tabs, you can `hook_form_alter()` your way to this via adding a `details` form element:

```
function MYMODULE_form_alter(&$form, $form_state, $form_id) {

  // @TODO: Add your own logic for filtering relevant node forms
  if (in_array($form_id, array('node_page_form', 'node_page_edit_form'))) {
    $form['example'] = array(
      '#type' => 'details',
      '#title' => t(''),
      '#description' => t(''),
      '#group' => 'advanced',
      '#open' => TRUE,
      'markup' => array(
        '#markup' => '<p>Random Markup</p>',
      ),
      '#weight' => 1000,
    );
  }
}

```

If you're looking to add markup that's not relevant to your node forms, you might be better off subtheming Seven and adding your own **node-edit-form.html.twig** template to your subtheme with your own markup additions:

```
<div class="layout-node-form clearfix">
  <div class="layout-region layout-region-node-main">
    {{ form|without('advanced', 'actions') }}
  </div>
  <div class="layout-region layout-region-node-secondary">
    {{ form.advanced }}
    <p>Random Markup</p>
  </div>
  <div class="layout-region layout-region-node-footer">
    {{ form.actions }}
  </div>
</div>

```
> 8 votes

# Answer
Just place your block under Main content block on content region in Seven theme, It would place your block in bottom of the form, then you could design that with custom css.

Add the `/node/*/edit` `/node/add/*` paths in the block visibility field, it would add the block only on the node edit page, else the block will show in all the admin pages.
> 1 votes

---
Tags: 8, blocks, forms
---


title: item.url generated at menu issue

text:
# Question
Title: item.url generated at menu issue
I am working on my client's project and they are using Drupal 8.

I discovered that when one uses http://example.com/index.php to access the webpage, the url generated by the menu items , the index.php part is included, i.e. http://example.com/index.php/aboutus instead of http://example.com/aboutus. And it leads to a wrong page.

And I checked with the template file which generates the menu, the url of the menu is generated by `{{item.url}}`, which item is one single item of items for the available variables in the menu templates.

> Available variables:
>
> -menu\_name: The machine name of the menu.
>
> -items: A nested list of menu items. Each menu item contains:
>
> -attributes: HTML attributes for the menu item.
>
> -below: The menu item child items.
>
> -title: The menu link title.
>
> -url: The menu link url, instance of \Drupal\Core\Url
>
> -localized\_options: Menu link localized options.

Therefore I am asking if there are ways to get rid of the "index.php" in this case and in order to avoid drupal generating wrong url? Thank you very much

# Answer
I think you may need to enable apache `mod_rewrite`. You can refer this answer as well. To enable `mod_rewrite`, use the following command:

```
a2enmod rewrite

```

Then you need to restart apache for the changes to reflect,

```
sudo /etc/init.d/apache2 restart

```

or

```
sudo service apache2 restart

```

Refer this page for information about clean urls, this might even help.
> 1 votes

# Answer
Render the menu item using link() function in your twig file for example,

```
{{ link(item.title, item.url) }}

```

I hope, it would solve your issues
> 0 votes

---
Tags: 8, uri
---


title: Generating arbitrary internal URLs

text:
# Question
Title: Generating arbitrary internal URLs
I'm generating the URL inside a controller in a custom module. The URL I generate is to pages on the same site, but not in the module. I want to append an arbitrary number of slugs to the end of the base URL. Some slugs depend on the return values from other API calls, so there's no way to predict how many there are, or what they will be.

I want to generate a `$url` variable of the form:

```
'www.base-path-of-website.com'/any/number/of/arbitrary/slugs

```

I have tried using:

```
Url::fromRoute()

```

But cannot figure out how to get the base route for the website from it. Or how to add arbitrary slugs.

This was trivial in Drupal 7 and earlier, but I cannot find how to do it in Drupal 8. In Drupal 8, how do you generate arbitrary internal URLs from a module? What should I be doing?

# Answer
From the Drupal API docs for `Url::fromRoute()`

> Creates a new Url object for a URL that has a Drupal route.
>
> This method is for URLs that have Drupal routes (that is, most pages generated by Drupal). For non-routed local URIs relative to the base path (like robots.txt) use Url::fromUri() with the base: scheme.

For this method, you need to provide the *route name* as defined in your module's **.routing.yml** file, along with an array of parameters in your route:

```
\Drupal\Core\Url::fromRoute('mymodule.my_route', array('route_param' => 'param_value'))->toString();

```

Alternatively, if you don't have a route to plug into you can use `Url::fromUri()` as the docs specified:

```
\Drupal\Core\Url::fromUri('base:/any/number/of/arbitrary/slugs',array('absolute' => TRUE))->toString();

```
> 3 votes

---
Tags: 8, routes, navigation
---


# Question
Title: How to disable cache on view with ID as contextual filter
I've got a view (block) wich fetches images from all nodes of content type x. I use these in a slider.

When I open node y, I only want to see the image of node y. So I add a contextual filter to filter on this node.

Here's the thing... It doesn't work. It caches the image, and always shows the cashed image. I already set the view caching to 'none' and disabled page caching.

I've got no clue how to disable the caching for this. Is this view caching? Is this block caching? Is this page caching?

# Answer
> 0 votes
Found the answer: I am using slick views for the slider.

Slick itself has cashing options. After disabling that caching, it worked like a charm.

to disable: * edit your view * open the format settings * Scroll down to the cache settings * Set it to no caching

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


# Question
Title: Programmatically creating a content type with file field in a custom module
I'm writing a custom module, which I've done before, but this is the first time I've tried to create a content type with fields. I implemented hook\_node\_info and the Content Type is showing up in the list of Content types in the dropdown from admin\_menu, however, when I browse to `admin/structure/types` it is not listed.

I implemented hook\_install and grabbed some code I found on another SO question. I have the code print out some debug info to my error log and it LOOKS like it all works, but when I browse to the Structure Content Type it doesn't show the field I added.

Here are hooks:

```
function mymod_node_info() {
  return array(
    'mymod_content' => array(
      'name' => t('My Mod'),
      'base' => 'mymod_content',
      'description' => t('A Description'),
    )
  );
}

function mymod_install() {
    error_log('mymod_install');
    $types = node_type_get_types();

    if ( ! field_info_field('field_mymod_myfile') ) {
        $field = array(
            'field_name' => 'field_mymod_myfile',
            'type' => 'file',
        );
        $created_field = field_create_field($field);
        error_log('---- field_create_field -----');
        error_log(var_export($created_field, true));
    }

    $instance = array(
        'field_name' => 'field_mymod_myfile',
        'entity_type' => 'mymod_content',
        'bundle' => 'mymod_content',
        'required' => TRUE,
    );
    $created_instance = field_create_instance($instance);
    error_log('---- field_create_instance -----');
    error_log(var_export($created_instance, true));
}

```

I can see a table called `field_data_field_mymod_myfile` in the database, so I know the first part worked. However, the table is empty.

The error log shows the `field_create_instance()` method returned this:

```
array (
  'field_name' => 'field_mymod_myfile',
  'entity_type' => 'mymod_content',
  'bundle' => 'mymod_content',
  'required' => true,
  'field_id' => '5',
)

```

Why doesn't my field show up on this content type?

# Answer
This isn't so much an answer as it is an expansion on the previous answer.

I found these two links very helpful in figuring out what the system needs for custom fields to be added to your custom module node type.

Best: http://www.sitepoint.com/creating-a-new-drupal-node-type/

Good additional info: http://public-action.org/content/drupal-7-field-api-drupal-7-adding-custom-content-type-custom-fields-field-api

The problem I had was that these (and every other example I can find online) are very specific examples without enough documentation to help me figure out a solution to my own usage case.

What helped was tenken's comment to the OP about using the Features module to get the arrays for the custom fields.

So I downloaded the Features module and enabled it: https://drupal.org/project/features

Then I created the fields on my content type, using the admin interface in Drupal like you normally would, that I wanted the module to create. Then I browsed to Structure \> Features \> Create feature and put in a bogus name (I used "test") for the feature and then over in the components area click on "Field Instances" and check the boxes for the custom fields. The fields are all named something like node-\[your node type machine name\]-\[field name\], so in my case since I wanted an image field it was node-novel\_section-field\_image.

After selecting the custom fields for my node type I then just clicked on "Download feature" and saved the .tar file to my desktop, opened it, opened the "test" folder then viewed the test.features.field\_base.inc and test.features.field\_instance.inc to get the arrays I needed for my fields.

Then I just used the structure outlined by that first link I posted and after that it worked perfectly. For me.

I could not find any documentation on the array structures needed for things like image fields and taxonomy reference fields and it seemed all other tutorials and help requests online are focused on specific things like text fields.

Hopefully anyone having the same trouble I was having will see this and be able to make their setup work using these examples and the Features module like I did.

Thanks to tenken for pointing out this functionality of the Features module, I'd never used it and didn't know it would do that.
> 7 votes

# Answer
This code that will be created new content type that should add into .install file.

**Adding hook\_install():**

```
<?php
function your_module_name_install() {
  // use get_t() to get the name of our localization function for translation
  // during install, when t() is not available.
  $t = get_t();

  // Define the node type.
  $node_example = array(
    'type' => 'node_example',
    'name' => $t('Example Node'),
    'base' => 'node_content',
    'description' => $t('This is an example node type with a few fields.'),
    'body_label' => $t('Example Description')
  );

  // Complete the node type definition by setting any defaults not explicitly
  // declared above.
  // http://api.drupal.org/api/function/node_type_set_defaults/7
  $content_type = node_type_set_defaults($node_example);
  node_add_body_field($content_type);

  // Save the content type
  node_type_save($content_type);
}
?>

```

**You should make drupal message and write this event to the log:**

```
<?php
function your_module_name_install() {
  $t = get_t();
  $node_example = array(
    'type' => 'node_example',
    'name' => $t('Example Node'),
    'base' => 'node_content',
    'description' => $t('This is an example node type with a few fields.'),
    'body_label' => $t('Example Description')
  );
  $content_type = node_type_set_defaults($node_example);
  node_add_body_field($content_type);
// Check if we create content type or update.
  $status = node_type_save($content_type);
// Replacement rule for the messages.
  $t_args = array('%name' => $content_type->name);
  if ($status == SAVED_UPDATED) { // update case
    drupal_set_message($t('The content type %name has been updated.', $t_args));
  }
  elseif ($status == SAVED_NEW) { // create case
    drupal_set_message($t('The content type %name has been added.', $t_args));
    watchdog('node', 'Added content type %name.', $t_args, WATCHDOG_NOTICE, l($t('view'), 'admin/structure/types'));
  }
}
?>

```

**Provide hook\_uninstall() to remove your content type** :

```
<?php
function your_module_name_uninstall() {
  // Gather all the example content that might have been created while this
  // module was enabled.  Simple selects still use db_query().
  // http://api.drupal.org/api/function/db_query/7
  $sql = 'SELECT nid FROM {node} n WHERE n.type = :type';
  $result = db_query($sql, array(':type' => 'node_example'));
  $nids = array();
  foreach ($result as $row) {
    $nids[] = $row->nid;
  }
  // Delete all the nodes at once
  // http://api.drupal.org/api/function/node_delete_multiple/7
  node_delete_multiple($nids);
  // Delete our content type
  // http://api.drupal.org/api/function/node_type_delete/7
  node_type_delete('node_example');
}
?>

```
> 4 votes

# Answer
This post is a bit out-dated, but if it helps, I’ve found this article to be very clear. It shows you how to create a new content type step-by-step.

Link to tutorial

```
<?php

/**
 * Implements hook_install().
 */
function book_install()
{

    $t = get_t();

    // Step 1 - Define the custom content type

    $content_type = array(

        'type'          => 'book',
        'name'          => $t('Book'),
        'description'   => $t('Create a new book'),
        'title_label'   => $t('Book title'),
        'base'          => 'node_content',
        'custom'        => TRUE,

    );

    $node_type = node_type_set_defaults($content_type);

    node_type_save($node_type);

    // Step 2 - Create new fields

    $fields = array(

        // Author’s name

        'book_author_name'  => array(

            'field_name'    => 'book_author_name',
            'type'          => 'text',
            'cardinality'   => 1,

        ),

        // Description

        'book_description'  => array(

            'field_name'    => 'book_description',
            'type'          => 'text_long',
            'cardinality'   => 1,

        ),

    );

    foreach( $fields as $field ) {

        field_create_field($field);

    }

    // Step 3 - Attach fields to content type

    $instances = array(

        // Author’s name

        'book_author_name'  => array(

            'field_name'   => 'book_author_name',
            'label'        => $t('Author Name'),
            'required'     => TRUE,
            'widget'       => array(
                'type'  => 'text_textfield'
            ),

        ),

        // Description

        'book_description'  => array(

            'field_name'   => 'book_description',
            'label'        => $t('Description'),
            'required'     => TRUE,
            'widget'       => array(
                'type'  => 'text_textarea'
            ),

        ),

    );

    foreach( $instances as $instance ) { // Loop through our instances

        $instance['entity_type']   = 'node';
        $instance['bundle']        = 'book'; // Attach the instance to our content type

        field_create_instance($instance);

    }

}

```
> 1 votes

---
Tags: 7, entities, installation, nodes
---


# Question
Title: Excluding Book children from a Custom view
We have a News site that displays all news articles on the homepage and subpages that display only those items tagged with a certain Taxonomy term. So for example we have a World News term so going to www.example.net/worldnews will only show those articles with that term. That works great.

Now we have a request to also filter on Book Content type, so that instead of showing just Article Content nodes we want Article and Book. For the Homepage we'd use the same sort of filter that we did for Article, and that works well. However on the subpages, Book parents AND children are showing up. Is there a way to make sure no children ever show up on the subpages ( but of course would still be accessible the usual way from the parent and siblings )? I've played around with Contextual Filters but can't quite get it right.

We do have some module code written that uses this View so it may be that I need to go that route and write some code, but would love to see if a View-only solution is possible.

# Answer
> 0 votes
This can be done with Normal filter in views.

Following is the configuration of the `filter UI`, You need to separate the both `content type` in the filter with `OR` and in the `Content Type: Book` page you need to `Book: Depth = 1`.

Now in the following image you can see the `Article` and `Book page titles`, First one without `Book: Depth =1`, Second one with `Book: Depth =1`.

Hence, You can see the views fetches the all articles and only parents books page.

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


# Question
Title: Update from 8.1.3 to 8.1.7 gives me a fatal error on most pages
After attempting to update to version 8.1.5 I received the

* "The website encountered an unexpected error. Please try again later."

error on many pages. I also get the following error in Recent Log Messages;

* "Drupal\Component\Plugin\Exception\PluginNotFoundException: The "2" plugin does not exist. in Drupal\Core\Plugin\DefaultPluginManager-\>doGetDefinition() (line 52 of /home/username/public\_html/domain/core/lib/Drupal/Component/Plugin/Discovery/DiscoveryTrait.php).

Any ideas what could be causing this or how to fix it?

**Update 2016/07/20**

I just tried once again to update from 8.1.3 to 8.1.7 and am getting the same errors. My 8.1.3 site was stable with no errors.

Specifically, the site has the following issues after updating and after running update.php several times.

* non-admin users can't log in; they receive the white screen of death upon login attempt, and can't even navigate to a different page than the default user page. The can only successfully logout using /user/logout to get back to the working frontpage and other working content pages.
* when logged in as admin, eveything seems to work except for the "extend" and "people" admin tabs, which result in a wsod.

The reports details show the following information after an unsuccessful attempt to access;

---

Type php

Date Wednesday, July 20, 2016 - 08:09

User admin

Location http://www.domain.com/admin/people

Referrer http://www.domain.com/admin/config/people/accounts

Message Drupal\Component\Plugin\Exception\PluginNotFoundException: The "2" plugin does not exist. in Drupal\Core\Plugin\DefaultPluginManager-\>doGetDefinition() (line 52 of /home/username/public\_html/domainfolder/core/lib/Drupal/Component/Plugin/Discovery/DiscoveryTrait.php).

Severity Error

Hostname @@@.@@.@@@.@@@

Operations

---

Type page not found

Date Wednesday, July 20, 2016 - 11:34

User admin

Location http://domain.com/quickedit/metadata

Referrer http://domain.com/node/preview/aabc334a-08fb-4d6a-8672-281dbe7a56e6/default

Message /quickedit/metadata

Severity Warning

Hostname 113.37.159.155

Operations

---

Type php

Date Wednesday, July 20, 2016 - 11:25

User admin

Location http://domain.com/node/add/lesson

Referrer http://domain.com/speakraku

Message Warning: mkdir(): File exists in Drupal\Component\PhpStorage\FileStorage-\>createDirectory() (line 165 of /home/username/public\_html/domain/core/lib/Drupal/Component/PhpStorage/FileStorage.php).

Severity Warning

Hostname 113.37.159.155

Operations

# Answer
> 0 votes
Fixed - tracked the problem down to the dev version of field permissions I was using. Updated to the latest dev version and all related issues were resolved.

---
Tags: users, debugging, updating, .htaccess
---


# Question
Title: Where does views's template files get saved?
I have created a view for content type = "`Article`" and have chosen "**FORMAT**" = GRID

**FORMAT**

**Format**:Grid | Settings

**Show**:Fields | Settings

My question is where does this view related template get saved?

I know Views default templates are located under "/core/modules/views/templates/" folder.

Here is the basic GRID template. How this grid template recognize a specific view that can render fields only of "ARTICLE" content type?

Is there any other template formed using view's machine name and row style?

Where should I place any view template so that it can effect all views of specific content type like "Article".

# Answer
> Where should I place any view template so that it can effect all views of specific content type like "Article".

While you can do this with nodes, I don't believe it's possible on views to affect all views of `x` content type. As you can see in FILTERS, there is a Type filter (=Article). It's just a filter.

The best option you have is to make it affect a specific view name and a view display.

EX: **views-view-grid--\[view-name\].html.twig**

if you want to specify a display then **views-view-grid--\[view-name\]--\[machine-name\].html.twig**

Then you copy the code from core's views-view-grid.html and paste it on your template file and modify as you wish.

If you want to alter fields, then use **views-view-fields--\[view-name\]--\[machine-name\].html.twig**

You place your custom template files in `/themes/[Your Theme]/templates` folder.
> 0 votes

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


# Question
Title: How to delete uninstalled modules via drush?
I have been wondering how one could clean up uninstalled modules in the modules folder. Perhaps by piping some drush output to rm rf...

I noticed drush pm list gives small modules that exist in larger enabled modules. Any tips?

```
drush pm-list --type=Module --no-core --status="Not installed"

```

# Answer
Drush is a tool for performing Drupal operations in the shell. If you've already uninstalled the module then there's nothing left in Drush's purview to do, just perform a rm on each module you need removed. `pm-list` has `--pipe` option that will spit out the module short name. You can use that output to find the correct directory and remove it. Something like...

```
drush pm-list --type=Module --pipe --no-core --status="Not installed" | while read -r module; do  find sites/all/modules -type d  -name "$module"; done

```

The remaining work here is more of question about bash (or your shell of choice) than Drush so I'll leave it to the reader to find his own solution.

It should also be mentioned scripting module folder deletion could be fraught with dangers (e.g. not every module is going to be at the same folder, you shouldn't be deleting submodules, etc.); you're better off manually inspecting a list of uninstalled modules (you shouldn't have *that many*) and removing them judiciously.
> 2 votes

# Answer
I found and tested this from here: https://www.drupal.org/node/855058#comment-3230936

```
rm -r `drush dd foo`

```

But read the thread about safety
> 1 votes

---
Tags: 7, drush
---


title: Term reference field won't display

text:
# Question
Title: Term reference field won't display
I'm trying to add tags to my blog posts on my Drupal 7 site. I've added the `Term Reference` field to the content type and when I add a blog post it is letting me add tags without a problem, however despite the field being visible in the 'Manage Display' tab I can't get them to show up when viewing the blog entry.

I know that the field is working because I have the `Metatag` module installed and that's producing metatags from the field token. I've checked the page source though and the field isn't even there but hidden because of CSS.

Anyone any ideas?

# Answer
It turns out that my theme was hiding any term reference fields by default, which I discovered after switching back to the default theme (thank you too @NoSssweat for suggesting I do this).

I created the theme using Artisteer (please keep comments about my decision to do so to a minimum - I only use it as a starting point) and following @JimmyKo's comment I found the following lines in the `node.tpl.php` file:

```
$terms = themename_art_terms_D7($content);
hide($content[$terms['#field_name']]);

```

After I commented these out the term reference field started appearing. Thinking back, I may have ticked an option in Artisteer to say that I didn't want tags to appear so I can't definitely lay the blame on the software!
> 0 votes

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


# Question
Title: Change the bulk operations confirmation page
How to change confirmation page in bulk operations?

Currently it is printing "You selected the following 4 items:".

I want to list titles of all items included in the bulk operation.

# Answer
> 0 votes
I assume that the entities are nodes, although the code can be easily adapted to any entity.

```
/**
 * Implements hook_form_alter.
 */
function my_module_form_alter(&$form, $form_state, $form_id) {

  if ($form_id == 'views_form_ADMIN_VIEW_MACHINE_NAME_system_1' && $form_state['step']== 'views_bulk_operations_confirm_form') {
    $items = array();
    $entity_type = 'node';
    $ids = $form_state['selection'];
    $entities = entity_load($entity_type, $ids);
    foreach ($entities as $entity) {
    $data = 'Title: '. $entity->title . '<br/>Created: <em>' . date('d/m/Y', $entity->created) . '</em>';
    $items[] = array(
    'data' => $data,
    'class' => array('item-class'),
    );
  }
    $title = '<h3>' . t('Nodes List:') . '</h3>';
    $type = 'ul';
    $attributes = array('class' => 'list-class-one list-class-two');
    $list = theme_item_list(array('items' => $items, 'title' => $title, 'type' => $type, 'attributes' => $attributes)); // Create the list.
    $form['description']['#markup'] = $list;
  }
}

```

---
Tags: 7
---


# Question
Title: feeds_ex module tests returns me fatal error
When I am running feeds\_ex test i got an error that says:

```
PHP Fatal error: Class 'TUnit' not found in /sites/all/modules/contrib/feeds_ex/src/Tests/FeedsExUnitTests.test on line 11

```

I am looking around in google and forums but nothing similar found.

Any solution appreciated!

# Answer
> 1 votes
Per the instructions for the Feeds extensible parsers module:

> To run tests locally, the TUnit module is required.

So you need to install the TUnit module, which contains the missing class.

---
Tags: 7, feeds, testing
---


# Question
Title: How to add link title in combine field filter
my view having combine field filter.it is working based on link field. the link field title is "test" and the url is "http://example.com".when i search using "test" it is not showing any result.if i search using "example" it shows correct content.how add the title also in combine field filter. anybodys can help? thanks advance!.

# Answer
* Add both link field title and link field url as fields in the views.
* If you don't need title field, please check "exclude from display".
* Then try searching using the content of title field(in your example. "test")
> 0 votes

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


# Question
Title: How is the node revision ID getting updated?
I have a question related to `_node_save_revision` function in drupal 7. I just want to know how I can get the new revision ID after saving a revision using this function

It is mentioned in the documentation here.

> The resulting revision ID is available afterward in `$node->vid`.

But how does this happen? Where is the new revision ID assigned to the node object?

# Answer
`drupal_write_record` handles that.

`vid` is the primary key on the `node_revision` table, as declared in `node_schema`, and `drupal_write_record` knows that because it introspects the schema when writing the record.

From there it just takes the ID returned from the database query, and populates the correct property on the object that was passed in. In this case, that's the `vid` property on the node object.
> 3 votes

---
Tags: 7, nodes
---