# Question
Title: How can I programmatically render a node's field respecting the view mode settings?
I want to render a node's field inside a block. It works like this:

```
<?php

if ($node) {
  if (isset($node->field_body_secondary) && $field = $node->field_body_secondary->value) {
    $markup = render($field);
    $build = array(
      '#type' => 'markup',
      '#markup' => $markup,
    );
  }
}

return $build;

```

But this is not 100% as if I would just render the field normally, making it visible in the view mode settings.

# Answer
> 2 votes
I think the viewmode should be applied to the node, not to the field. So you need to get the viewbuilder and render the node. Afterwards you can pick the rendered array for the field from the node'r render array. Kind of like this:

```
$vb = [EntityTypeManager]->getViewBuilder('node'); // Drupal\node\NodeViewBuilder
$nodeview = $vb->view($node, $viewmode);
$fieldrenderarray = $nodeview[youfield-here];

```

P.S. You need to "\[EntityTypeManager\]" anyhow injected as @entity\_type.manager service. Or get it in your Block-Plugin create() from $container-\>get('entity\_type.manager').

# Answer
> 50 votes
To render a single field with the display setting of a view mode you can use the `view()` method of the field:

Example for rendering the image the way it's configured in the node's teaser view-mode:

```
$build['image'] = $node->field_image->view('teaser');

```

Or the body as it's configured in the node's full view-mode:

```
$build['body'] = $node->body->view('full');

```

Or if you want to have more fine-grained control, you can programmatically recreate how Drupal is doing view-modes:

```
$display_options = [
  'label' => 'hidden',
  'type' => 'entity_reference_entity_view',
  'settings' => [
    'view_mode' => 'some_media_image_view_mode',
  ],
];
$build['image'] = $node->field_image->view($display_options);

```

You can figure out the type/settings by inspecting the HTML on the view-modes form (e.g. /admin/structure/types/manage//display/full ) or export the configuration and inspect the YAML files.

# Answer
> 8 votes
This answer builds on https://drupal.stackexchange.com/a/208061/394

```
// Designate the field we want to render.
$field_name = 'body';
// Retrieve a render array for that field with the given view mode.
$render_array = $entity->$field_name->view('full');
// Render the result.
\Drupal::service('renderer')->renderRoot($render_array);

```

To completely programmatically render the field you finish by calling `renderRoot()`, which establishes a separate render context from what typical page responses would use -- a single render context for a request or sub-request. We could also use `renderPlain()`, but then it would escape all the things.

In the Drush repl but not in normal page execution, this threw a warning for me:

```
PHP warning:  DOMDocument::loadHTML(): Tag drupal-entity invalid in Entity, line: 1 in /drupal/core/lib/Drupal/Component/Utility/Html.php on line 286

```

# Answer
> 5 votes
Thanks to Rainer Feike's answer I came to the solution:

```
<?php

public function build() {
  $node = \Drupal::routeMatch()->getParameter('node');
  $build = array();
  $markup = array();

  $fieldsToRender = array(
    'field_node_ref', 'field_foo', 'field_bar',
  );

  $viewmode = 'default';
  $entityType = 'node';
  $display = entity_get_display($entityType, $node->getType(), $viewmode);
  $viewBuilder = \Drupal::entityTypeManager()->getViewBuilder($entityType);

  foreach ($fieldsToRender as $field_name) {
    if (isset($node->{$field_name}) && $field = $node->{$field_name}) {
      $fieldRenderable = $viewBuilder->viewField($field, $display->getComponent($field_name));
      if (count($fieldRenderable) &&! empty($fieldRenderable)) {
        $markup[] = \Drupal::service('renderer')->renderRoot($fieldRenderable);
      }
    }
  }

  if (count($markup)) {
    $build = array(
      '#type' => 'markup',
      '#markup' => implode("", $markup),
    );
  }

  return $build;

}

```

Using `$viewBuilder->viewField` I can render any fields separately I need. I just need to find out how to add caching depending on the view mode settings, but this is another question :)

# Answer
> 3 votes
related to Alex's answer, here is how I modified it to use config\_pages and build a global\_footer block:

```
<?php

public function build() {
$config_name = 'global_footer';
$config = config_pages_config($config_name);
$build = array();
$markup = array();

$fieldsToRender = array(
  'field_body', 'field_foo', 'field_bar'
);

$viewmode = 'default';
$entityType = 'config_pages';
$display = entity_get_display($entityType, $config_name, $viewmode);
$viewBuilder = \Drupal::entityTypeManager()->getViewBuilder($entityType);

foreach ($fieldsToRender as $field_name) {
  if (isset($config->{$field_name}) && $field = $config->{$field_name}) {
    $fieldRenderable = $viewBuilder->viewField($field, $display->getComponent($field_name));
    if (count($fieldRenderable) &&! empty($fieldRenderable)) {
      $markup[] = \Drupal::service('renderer')->renderRoot($fieldRenderable);
    }
  }
}

if (count($markup)) {
  $build = array(
    '#type' => 'markup',
    '#markup' => implode("", $markup),
  );
}

return $build;

}

```

It's probably better to render arbitrary fields from a config\_pages setup as opposed to pulling data from a node, but I guess it really depends on the specific use-case as to which method is best.

---
Tags: entities, 8
---


# Question
Title: how to print value of a taxonomy field to headline with node.html.twig?
field\_test1 is a taxonomy field like fields\_tags.

`{{ content.field_test1 }}` prints the title and the value (not in teaser - why not?). I only want the **value** and want to print it in the header of the node before `{{ label }}`.

`{{ content.field_test1.value }}` or `{{ node.field_test1.value }}` don't work.

`{{ node.field_example.value }}` seems to work only for "usual" fields, but not for taxonomy fields.

How to do that?

(I've read the book of Chaz Chumley, but found no solution. I've got an answer of 4k4 in another thread, but I didn't understand. Therefore I've clarified my question here.)

# Answer
That's because a taxonomy field has no values. It contains entities, which are the referenced terms. You get the first term with `.entity` and then you can get the values inside of the term, for example if the term would have a field\_test2:

```
{{ node.field_test1.entity.field_test2.value }}

```

Or simply the term label (no `.value` needed for this):

```
{{ node.field_test1.entity.label }}

```

If you need translation use the `|translation` filter of the module Twig Tweak.
> 2 votes

---
Tags: theming, 8
---


# Question
Title: Drupal 8 - Bootstrap paragraphs not rendering color and width classes
I have installed bootstrap paragraphs module and when setting the color and width to the "Simple" bundle or any default bundles that comes with "Bootstrap Paragraphs" the classes are not being rendered on the div.

Please see image below: The classes should have been added to the wrapping div.

This is how the source looks like for this paragraph.

Am I missing anything?

Thanks in advance.

# Answer
> 2 votes
From your screenshots, it looks like it is adding template suggestions back in for the width and color fields. That makes it ignore what we are specifying in the Paragraphs bundle level templates, to print the content without those two fields.

My guess is that comes from the Field Layout module.

---
Tags: theming, 8, paragraphs
---


# Question
Title: I want to link file in views to files/fid
I have a content type, which has video and image attachment. In the view created on this content type, the table shows the thumbnails of video and image file. I want to link thumbnails to files/fileid. And not sites/all/default/files/filename....I want to link to file-id and not generic file... Tried rewrite results as a link but the lin there doesn't supports the tokens (file:fid or file:filename)..

# Answer
> 0 votes
Adding a field above the field in the list doesnt works because, he has build content on content type that has attachment, and not mere files..Means the view is not build on files so it will not have the field file:filename or file:fid... The best solution is to use custom formatter module {https://www.drupal.org/project/custom\_formatters} and in that use html plus tokens with following code

```
<a href="/?q=file/[file:fid]/"><img src="[formatted_field-image:image_url:image_style-media_thumbnail]" alt="[field_property:alt]" title="[field_property:title]" /></a>

```

This will give the required link to the thumbnail, if you dont want thumbnail you can put text there....

and then in views select the custom formatter for the required image field...

---
Tags: views
---


# Question
Title: Remove orphaned module data after uninstall
I have installed the xmlsitemap module, which is in alpha state. The module has an incomplete uninstall routine. Right now I am getting this error at /admin/config:

> User warning: The following module is missing from the file system: xmlsitemap in drupal\_get\_filename() (line 240 of core/includes/bootstrap.inc). drupal\_get\_filename('module', 'xmlsitemap') (Line: 263) drupal\_get\_path('module', 'xmlsitemap') (Line: 134) module\_load\_include('install', 'xmlsitemap') (Line: 93) module\_load\_install('xmlsitemap') (Line: 82) drupal\_load\_updates() (Line: 109) Drupal\system\SystemManager-\>listRequirements() (Line: 96) Drupal\system\SystemManager-\>checkRequirements() (Line: 102) Drupal\system\Controller\SystemController-\>overview('system.admin\_config') call\_user\_func\_array(Array, Array) (Line: 123) Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber-\>Drupal\Core\EventSubscriber{closure}() (Line: 574) Drupal\Core\Render\Renderer-\>executeInRenderContext(Object, Object) (Line: 124) Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber-\>wrapControllerExecutionInRenderContext(Array, Array) (Line: 97) Drupal\Core\EventSubscriber\EarlyRenderingControllerWrapperSubscriber-\>Drupal\Core\EventSubscriber{closure}() call\_user\_func\_array(Object, Array) (Line: 144) Symfony\Component\HttpKernel\HttpKernel-\>handleRaw(Object, 1) (Line: 64) Symfony\Component\HttpKernel\HttpKernel-\>handle(Object, 1, 1) (Line: 57) Drupal\Core\StackMiddleware\Session-\>handle(Object, 1, 1) (Line: 47) Drupal\Core\StackMiddleware\KernelPreHandle-\>handle(Object, 1, 1) (Line: 99) Drupal\page\_cache\StackMiddleware\PageCache-\>pass(Object, 1, 1) (Line: 78) Drupal\page\_cache\StackMiddleware\PageCache-\>handle(Object, 1, 1) (Line: 47) Drupal\Core\StackMiddleware\ReverseProxyMiddleware-\>handle(Object, 1, 1) (Line: 50) Drupal\Core\StackMiddleware\NegotiationMiddleware-\>handle(Object, 1, 1) (Line: 23) Stack\StackedHttpKernel-\>handle(Object, 1, 1) (Line: 656) Drupal\Core\DrupalKernel-\>handle(Object) (Line: 19)

There are dozens of entries in my database, which are related to this module. Is there any quick way, to remove the module's orphaned data?

# Answer
> 1 votes
Use following database query to remove the module:

### Drupal 8

```
DELETE FROM key_value WHERE collection='system.schema' AND name='module_name'

```

### Drupal 7

```
DELETE from system where name = 'old_module1' AND type = 'module'

```

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

---
Tags: installation
---


title: Get all nodes with empty taxonomies

text:
# Question
Title: Get all nodes with empty taxonomies
I'm trying to fetch all nodes who's term reference field has no value or NULL.

```
$query = \Drupal::entityQuery('node')
    ->condition('type', 'mycontenttype', '=')
    ->condition('field_grade_level.entity.name', '');

    $nids = $query->execute();
    return $nids;

```

But it doesn't seem to work, giving empty results. Can anyone help what's wrong with the query?

# Answer
> 2 votes
You query is looking for nodes that are tagged with a term that has an empty label. Obviously that's not what you want. What you're looking for is notExists():

```
$query = \Drupal::entityQuery('node')
  ->condition('type', 'mycontenttype', '=')
  ->notExists('field_grade_level');

$nids = $query->execute();
return $nids;

```

---
Tags: 8, nodes
---


title: Import password hash

text:
# Question
Title: Import password hash
I'm trying to migrate users from a non Drupal System into Drupal. I implemented my own CSV import script which basically generates Drupal user entities.

I already managed to teach Drupal how to handle the password hashes from the old system so that on first login of an "old" user, the old hash is getting replaced with a new one.

When creating a user account, Drupal automatically hashes the input for the *Password* field. I guess this is happening in the post save hook of the user entity.

How can I create user entities which will have my old hash inside of the pass field?

# Answer
> 0 votes
I figured it out by myself now. In case someone runs into the same problem: Updating the database directly avoids the problem of rehashing:

```
$query = \Drupal::database()->update('users_field_data')->fields([
    'pass' =>$prefixed_password_hash,
])->condition('uid',$user->id());

$query->execute();

```

---
Tags: users
---


title: Quick Edit module permissions

text:
# Question
Title: Quick Edit module permissions
I have enabled Quick Edit module on my Drupal 8 website and it's working ok, I have edit link in the toolbar to show all edit icons for edit menu on page.

Problem is in new user role. I have new user role and I enabled `Access in-place editing` permission for users in this role, but there is no option to edit anything on the page or edit link in toolbar.

What I'm missing? Is there some additional permission that I need to grant for this role (they already have permission to administer blocks)?

# Answer
> 13 votes
I found the problem, it's stupid.

I forgot to add permission to access to contextual links for this user role, so that's it.

---
Tags: 8, blocks, users, entities
---


# Question
Title: How to add a property to a field type having data
I have a custom field type. Now I need to add an additional property to it.

I added the new property to `propertyDefinitions()` and `schema()` methods.

What should I do in the update hook? The field type is already in use, and fields have values stored in the database.

# Answer
> 3 votes
I ended up using the following code.

```
function my_module_update_8001() {
  $field_type = 'my_field_type';
  $new_property = 'my_new_property';

  $manager = \Drupal::entityDefinitionUpdateManager();
  $field_map = \Drupal::entityManager()->getFieldMapByFieldType($field_type);
  foreach ($field_map as $entity_type_id => $fields) {
    foreach (array_keys($fields) as $field_name) {
      $field_storage_definition = $manager->getFieldStorageDefinition($field_name, $entity_type_id);
      $storage = \Drupal::entityTypeManager()->getStorage($entity_type_id);
      if ($storage instanceof \Drupal\Core\Entity\Sql\SqlContentEntityStorage) {
        $table_mapping = $storage->getTableMapping([
          // We pass only one storage definition to make
          // \Drupal\Core\Entity\Sql\DefaultTableMapping::getDedicatedTableNames()
          // return only tables we need.
          $field_name => $field_storage_definition,
        ]);
        $table_names = $table_mapping->getDedicatedTableNames();
        $columns = $table_mapping->getColumnNames($field_name);
        foreach ($table_names as $table_name) {
          $field_schema = $field_storage_definition->getSchema();
          \Drupal::database()
            ->schema()
            ->addField($table_name, $columns[$new_property], $field_schema['columns'][$new_property]);
        }
      }
      $manager->updateFieldStorageDefinition($field_storage_definition);
    }
  }
}

```

# Answer
> 2 votes
Based on Alex' answer, I updated the code with non-deprecated code (entity\_field.manager). Also fixed two small variable mistakes. This piece of code can be added to .install files for example and will update *all entities* containing the field you'd like to update.

```
$field_type = 'fieldtype_to_be_updated';
$new_property = 'new_property_to_be_added';

$manager = \Drupal::entityDefinitionUpdateManager();
$field_map = \Drupal::service('entity_field.manager')->getFieldMapByFieldType($field_type);

foreach ($field_map as $entity_type_id => $fields) {

  foreach (array_keys($fields) as $field_name) {
    $field_storage_definition = $manager->getFieldStorageDefinition($field_name, $entity_type_id);
    $storage = \Drupal::entityTypeManager()->getStorage($entity_type_id);

    if ($storage instanceof \Drupal\Core\Entity\Sql\SqlContentEntityStorage) {
      $table_mapping = $storage->getTableMapping([
        $field_name => $field_storage_definition,
      ]);
      $table_names = $table_mapping->getDedicatedTableNames();
      $columns = $table_mapping->getColumnNames($field_name);

      foreach ($table_names as $table_name) {
        $field_schema = $field_storage_definition->getSchema();
        $schema = \Drupal::database()->schema();
        $field_exists = $schema->fieldExists($table_name, $columns[$new_property]);
        $table_exists = $schema->tableExists($table_name);

        if (!$field_exists && $table_exists) {
          $schema->addField($table_name, $columns[$new_property], $field_schema['columns'][$new_property]);
        }
      }
    }
    $manager->updateFieldStorageDefinition($field_storage_definition);
  }
}

```

# Answer
> 0 votes
Based on Leksats answer I added a few lines to prevent some possible exceptions...

```
  $field_type = 'fieldtype';
  $new_property = 'newproperty';

  $manager = \Drupal::entityDefinitionUpdateManager();
  $field_map = \Drupal::entityManager()->getFieldMapByFieldType($field_type);

  foreach ($field_map as $entity_type_id => $fields) {

    foreach (array_keys($fields) as $field_name) {
      $field_storage_definition = $manager->getFieldStorageDefinition($field_name, $entity_type_id);
      $storage = \Drupal::entityTypeManager()->getStorage($entity_type_id);

      if ($storage instanceof \Drupal\Core\Entity\Sql\SqlContentEntityStorage) {
        $table_mapping = $storage->getTableMapping([
          // We pass only one storage definition to make
          // \Drupal\Core\Entity\Sql\DefaultTableMapping::getDedicatedTableNames()
          // return only tables we need.
          $field_name => $field_storage_definition,
        ]);
        $table_names = $table_mapping->getDedicatedTableNames();
        $columns = $table_mapping->getColumnNames($field_name);

        foreach ($table_names as $table_name) {
          $field_schema = $field_storage_definition->getSchema();
          $schema = \Drupal::database()->schema();
          $field_exists = $schema->fieldExists($table_name, $columns[$new_property]);
          $table_exists = $schema->tableExists($table_name);

          if (!$fieldExists && $tableExists) {
            $schema->addField($table_name, $columns[$new_property], $field_schema['columns'][$new_property]);
          }
        }
      }
      $manager->updateFieldStorageDefinition($field_storage_definition);
    }
  }

```

---
Tags: 8
---


# Question
Title: Best way of having Pathauto based off node title, but not tied to it?
Sorry for the poorly worded question, I'll try to better explain myself.

I'm swapping (not migrating) from WP to Drupal and I'm trying to replicate WP's URL feature. I want it to initially be based off the title of the node ("My First Blog Post" =\> "my-first-blog-post")

What I'm not wanting is Pathauto to be directly linked to the title, so I can update the title to something like "My First Blog Post (Updated 5/4/2017)" without having to worry about the URL changing. I want the URL to be easily editable if the need rises, I just don't want it tied to the title.

Would the best way just be to add an extra field, and manually enter a 'URL title' in there?

# Answer
The contributed module Pathauto will provide you a setting to set your own alias urls in the add content page.

Suppose you are adding a content of type basic page (using `node/add/page`), at the bottom there will be an *url path settings* tab where you can uncheck the 'Generate automatic URL alias' option and set your own path alias for the page.
> 2 votes

---
Tags: path-aliases
---


# Question
Title: How to know if a site is Multilingual programmatically?
In Drupal 7 I used drupal\_multilingual() to know if a site is multilingual, but this function was renamed in Drupal 8 to language\_multilingual(), the problem is that it seems that language\_multilingual() is not longer available.

I found that LanguageManager::isMultilingual should return:

> bool TRUE if more than one language is added, FALSE otherwise.

But when you go to see the code always FALSE is returned.

```
public function isMultilingual() {
  return FALSE;
}

```

This is an error or I missing something?

# Answer
> 1 votes
The default `LanguageManager` always returns false when you check for multilingual, because you need to install the Language module to configure a multilingual site. This module provides a proper check for multilingual by replacing the class `LanguageManager` with `ConfigurableLanguageManager`:

*Drupal\language\LanguageServiceProvider::alter*

```
  public function alter(ContainerBuilder $container) {
    $definition = $container->getDefinition('language_manager');
    $definition->setClass('Drupal\language\ConfigurableLanguageManager')
    ...

```

*Drupal\language\ConfigurableLanguageManager::isMultilingual()*

```
public function isMultilingual() {
    return count($this->getLanguages(LanguageInterface::STATE_CONFIGURABLE)) > 1;
  }

```

So you can use the service `language_manager`, injected in a class or from the static service container wrapper `Drupal`:

*Drupal::languageManager()*

```
  /**
   * Returns the language manager service.
   *
   * @return \Drupal\Core\Language\LanguageManagerInterface
   *   The language manager.
   */
  public static function languageManager() {
    return static::getContainer()->get('language_manager');
  }

```

to use in all cases the correct class:

`\Drupal::languageManager()->isMultilingual()`

# Answer
> 2 votes
Searching I found in drupalcontrib a reference to the language\_multilingual() function that show the following code:

```
function language_multilingual() {
  return Drupal::languageManager()->isMultilingual();
}

```

So I used `Drupal::languageManager()->isMultilingual();` and it seems that returns the good value.

I'll do tomorrow a test in a not multilingual site to confirm.

# Answer
> 2 votes
The `LanguageManager` class is the wrong class to use, since it is defined as follows.

> Class responsible for providing language support on language-unaware sites.

Given that description, and the fact there is a service using that class, the correct code should instantiate a service, which is what the code in install.core.inc does. (See `install_tasks()`.)

```
  // Determine whether a translation file must be imported during the
  // 'install_import_translations' task. Import when a non-English language is
  // available and selected. Also we will need translations even if the
  // installer language is English but there are other languages on the system.
  $needs_translations = (count($install_state['translations']) > 1 && !empty($install_state['parameters']['langcode']) && $install_state['parameters']['langcode'] != 'en') || \Drupal::languageManager()->isMultilingual();

```

So, the correct code to use in procedural code is the following.

```
$is_multi_lingual = \Drupal::languageManager()->isMultilingual();

```

When using a class, and when it is possible, the service should be injected, and it instance saved in a object property (e.g. `$this->languageManager`). In that case, the code is the following.

```
$is_multi_lingual = $this->languageManager->isMultilingual();

```

The service ID for the language manager is language\_manager.

---
Tags: 8, i18n-l10n
---


# Question
Title: How to Make field required depending on other field?
I have 2 fields in my content type "blog"

1)promote to front page(boolen field with yes or no option)

2)Hero Image(image field)

If user selects "yes" option in promote to front page field ,the Hero image field should become required.

How it can be possible?

# Answer
You can do this with the Conditional Fields module.

It allows you to configure dependencies between fields (visible / required / etc.). It's still a development release, but it should work.
> 0 votes

---
Tags: 8
---


# Question
Title: How to set target="_blank" for links in CKEditor
I use CKEditor in Drupal 8. I want that every link will open in a new tab of browser. I want that the code look like this

```
    <a href="#" target="_blank">my link</a>

```

But if I use the link Button in editor I do not have choice for target blank. I only can fill in the url of link and the code looks like this

```
    <a href="#">my link</a>

```

Any idea what I have to do for changing this?

# Answer
## D8 Editor Advanced link module

> Enhances the link Dialog in D8 CKEditor. Allows to define the following attributes:
>
> * title
> * class
> * id target
> * rel
> 21 votes

# Answer
You can use the Linkit module and add a "target" attribute at admin/config/content/linkit/manage/default/attributes/add

It has two options:

* Selectlist with predefined targets.

* Simple checkbox to allow links to be opened in a new browser window or tab.
> 6 votes

# Answer
If you want *every* link to open in a new window, it'd be better to not use the Editor Advanced Link module, but instead add a filter to your text format that sets `target=_blank` on every `<a>`.
> 5 votes

---
Tags: 8, navigation, wysiwyg
---


# Question
Title: How to open external links in new window?
I'm using the "filtered HTML" text format in the node body with the "convert URLs into links" option enabled. I would like to have all external links open in a new window. How can I do that?

# Answer
> 7 votes
The External Links module does exactly that:

> External Links is a small module used to differentiate between internal and external links. Using jQuery, it will find all external links on a page and add an external icon indicating it will take you offsite or a mail icon for mailto: links.
>
> Configuration options:
>
> * Apply icons to either mailto: or external links or both.
> * **Configure external links to open in a new window.**
> * A confirmation message when leaving the site.
> * Regular expression inclusion and exclusion of links considered external.
> * CSS selector inclusion and exclusion of elements for processing

# Answer
> 5 votes
If you don't want to use JavaScript for this, you need to implement `theme_link(&variables)` in your template.php file.

Test `$variables['path']` for scheme declaration at the beginning. If there is none, leave it be. If there is some, add target to attributes:

```
$variables['options']['attributes']['target'] = '_blank';

```

Of course it bases on assumption that your HTML version supports `target` attribute, but this version is also theme-dependent, and most browsers will respect it even if technically it shouldn't be there.

# Answer
> 1 votes
You can use the Linkit module and add a "target" attribute at admin/config/content/linkit/manage/default/attributes/add

It has two options:

* Selectlist with predefined targets.

* Simple checkbox to allow links to be opened in a new browser window or tab.

---
Tags: 7, navigation
---


# Question
Title: How to adapt Twitter Bootstrap´s css classes to drupal menus?
I´m traying to adapt the Twitter´s Bootstrap top menu to Drupal menu system. Up until now, unsuccessfully. I´m using Drupal module **nicemenus** to show them in dropdowns.

This is the hand made menu list using Bootstrap´s css:

```
    <div class="navbar navbar-fixed-top">
      <div class="navbar-inner" style="padding-left: 0px;">
        <div class="container">
          <ul class="nav">
            <li class="dropdown">
                <a href="#" class="dropdown-toggle" data-toggle="dropdown">Dropdown 1
                <b class="caret"></b></a>
                <ul class="dropdown-menu">
                    <li><a href="#"><i class="icon-star"></i> Item 1</a></li>
                    <li><a href="#"><i class="icon-star"></i> Item 2</a></li>
                </ul>
            </li>
            <li><a href="#">Normal Menu Link without dropdown</a></li>
          </ul>
        </div>
      </div>
    </div>

```

And this is the Menu output with nicemenus, as you can see Bootstrap is so much easier to understand.

```
<div id="block-nice-menus-1" class="block block-nice-menus block-1 block-nice-menus-1 odd block-without-title">
  <div class="block-inner clearfix">

    <div class="content clearfix">
      <ul id="nice-menu-1" class="nice-menu nice-menu-down sf-js-enabled">
        <li class="menu-5674 menu-path-liganetnet  first   odd"><a href="">Link without Dropdowns</a></li>
        <li class="menu-267 menuparent  menu-path-front   even"><a style="dropdown" class="dropdown active" href="/">Dropdown Link 1</a>
            <ul style="display: none; visibility: hidden;">
                <li class="menu-2280 menu-path-node-196  first odd "><a href="">Item 1</a></li>
                <li class="menu-270 menu-path-node-197 even "><a title="" href="">Item 2</a></li>
                <li class="menu-271 menu-path-node-1464   odd   last "><a title="" href="">Item 3</a></li>
            </ul>
        </li>

        <li class="menu-268 menuparent  menu-path-front   odd"><a class="active" href="/">Dropdown Link 2</a>
            <ul style="display: none; visibility: hidden;">
                <li class="menu-274 menu-path-node-214  first   odd  "><a title="" href="">Item 1</a></li>
                <li class="menu-273 menu-path-node-213   even  "><a title="" href="">Item 2</a></li>
            </ul>
        </li>
      </ul>
    </div>
  </div>
</div>

```

I´ve installed menu\_attributes module, but when I add to it some classes they are added to the tag only. How could I transform those css classes programatically?

Doing a print\_r(), I´ve found this:

```
                            [sidebar_second] => Array
                                (
                                    [nice_menus_1] => Array
                                        (
                                            [#markup] =>

Link 1 without Dropdown
Dropdown 1
Dropdown 2
Dropdown 3

                                            [#contextual_links] => Array
                                                (
                                                    [block] => Array
                                                        (
                                                            [0] => admin/structure/block/manage
                                                            [1] => Array
                                                                (
                                                                    [0] => nice_menus
                                                                    [1] => 1
                                                                )

                                                        )

                                                )

                                            [#block] => stdClass Object
                                                (
                                                    [module] => nice_menus
                                                    [delta] => 1
                                                    [theme] => liganet
                                                    [status] => 1
                                                    [weight] => -62
                                                    [region] => sidebar_second
                                                    [custom] => 0
                                                    [visibility] => 0
                                                    [pages] =>
                                                    [title] =>
                                                    [bid] => 744
                                                    [cache] => -1
                                                    [subject] =>
                                                )

```

I thought that it could be done with the parent menu variable printed in the page template and then printing the children vars inside the classes? How may I do that with php?

Thanks for your help!

# Answer
> 1 votes
## How to add/remove classes from menu output

Add the three functions below to the file *template.php* in your theme folder. Make sure the function names start with the name of your theme. The suffix `__main_menu` indicates the machine name of the menu you want to alter. Once the functions are added to your file, clear all caches.

1 ) theme\_menu\_tree(). This adds the "nav" class to the `<ul>` element. If we left things here it would be applied to the parent and all child menus. Since we only want this applied to the parent, let's keep going.

```
function mytheme_menu_tree__main_menu($variables) {
  return '<ul class="nav">' . $variables['tree'] . '</ul>';
}

```

2 ) theme\_menu\_link(). We have added only two lines to the original function which are commented below. The first adds the "dropdown" class to any `<li>` element that contains a child menu. The second declares a new theme wrapper specifically for the child menus.

You can optionally strip away existing classes with `$element['#attributes']['class'] = 'dropdown';` (remove the empty square brackets).

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

  if ($element['#below']) {

    // Add class to this list element.
    $element['#attributes']['class'][] = 'dropdown';

    // Declare a new theme wrapper for this list item's child menu.
    $element['#below']['#theme_wrappers'][0] = 'menu_tree__main_menu_children';

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

```

3 ) Custom theme function. This is our custom implementation of `theme_menu_tree` that we just declared above. It adds the class "dropdown-menu" to all child menus.

```
function mytheme_menu_tree__main_menu_children($variables) {
  return '<ul class="dropdown-menu">' . $variables['tree']    . '</ul>';
}

```

**Notes:**

* Be warned that removing classes could alter the functionality of the menu!
* This technique will only affect menu output; that is, everything between `<ul id="nice-menu-1">`..`</ul>` in the example pasted above. To remove the wrapper elements you should override block.tpl.php as described on this handbook page.

**More helpful links:**

# Answer
> 0 votes
Install Bootsrap theme and set this theme as base theme of your own theme. All menus will output as you need in this case, because Bootsrap theme has all rewrite functions

---
Tags: 7, routes
---


# Question
Title: How do I enable the browser spell checker in WYSIWYG editor?
I want to use the in-browser spell checker within the Drupal 7 WYSIWYG editor, which is currently disabled by default.

I found this post but the settings aren't availble in my Drupal module. When I go to Home » Administration » Configuration » Content authoring there doesn't seem to be a place to enable or turn off the disabled browser spell checker. Thanks for any help!

# Answer
> 0 votes
The Check Spelling plugin is only included with CKEditor Standard and Full by default.

For the CKEditor module spell checking is enabled via the profiles.

Go to Configuration \> Content authoring \> CKEditor and edit each profile you to to it display on. Then under Editor Appearance drag the appropriate buttons to the "Current toolbar"

If you are using the WYSIWYG module it is also enabled through the profiles.

Go to Configuration \> Content authoring \> Wysiwyg profiles and edit each profile you want it to display on and check the "Check Spelling" option.

With CKEditor 4 you must enable "Spell check as you type" since the buttons have been merged into one with WYSIWYG.

---
Tags: 7, wysiwyg
---


# Question
Title: twig debug what does % mean - name of page.twig
I wonder about the "%". What does that mean?

```
<!-- THEME DEBUG -->
<!-- THEME HOOK: 'page' -->
<!-- FILE NAME SUGGESTIONS:
  * page--node--31.html.twig
  * page--node--%.html.twig
  * page--node.html.twig
  x page.html.twig
-->

```

And what names are possible? I need a page for a specific and custom block for viewing the whole content. I need something like this, but do not know how to do it right.

```
page--node--[my-custom-block]

```

# Answer
```
page--node--%.html.twig

```

This would be a universal template for page level views of any content type. So if you wanted to have the same template for different content types you could use this convention. If you need different templates for each content type you could apply:

```
page--node--[content type machine name].html.twig

```
> 0 votes

---
Tags: theming, 8
---


# Question
Title: Get the first instance of a field where it's not null from rows
I've got a view page, which is pulling together quite a few content types. All of these content types have a field called `field_image`, however some are not required and/or are missing.

I basically need to grab the first (latest - sorting by author date in my view settings) row, check if there's a `field_image`, if there is, we can just return that field, if not, repeat.

I thought about a few different ways of doing this, and I thought that I'd make it a Twig command for ease. My issue is that I can't seem to get the single field I'm looking for.

**My Twig function is currently:**

```
public function get_first_instance($field, $rows) {
  foreach($rows[0]['#rows'] as $row) {
    dump($row['#row']);
    exit;
  }
}

```

I'm running the Twig command from my `views-view--my-content-type--page.html.twig` template, passing a string, and `rows`.

I can see that the `field_image` is located in `_entity > #fields > field_image`, I'm just not sure how to reference this, or what function to use to load the entity?

Thanks for any help in advance.

# Answer
**Solved it, makes sense now!**

```
public function get_first_instance($field, $rows) {

  foreach($rows[0]['#rows'] as $row) {
    $entity = $row['#row']->_entity;

    if($entity->hasField($field)) {
      $value = $entity->get($field)->getValue();

      if(! empty($value)) {
        return $value;
      }
    }
  }

  return dump('Field not found: '.$field);
}

```
> 0 votes

---
Tags: theming, 8
---


# Question
Title: rules condition to check whether user has flagged another
Hi I have two user roles, client and consultant. Currently a client is able to flag a consultant as their selected consultant.

Now here is where im stuck. I am looking to use rules to display a message to clients whom have not flagged a consultant yet. How would i go about setting up this condition within a rule?

# Answer
Okay so I managed to work something out although I dont entire understand why its working. I created a data comparison condition and set the DATA TO COMPARE to "account:flag-consultant-flag-flagged" and DATA VALUE is set to "account:flag-consultant-flag-user".

Here was my logic although I thought it would do the exact opposite. I figured that if i compared all the flagged consultants with the consultants flagged by the current user, there should be a match and so the condition would be true. Weirdly though the rule is firing for users that didnt select a consultant so it turns out it did the exact opposite. If anyone is able to give some clarity, it would be much appreciated.
> 0 votes

---
Tags: rules, flags
---


# Question
Title: How do I configure the Block Access module?
I want to use the *Block Access* module, but I don't know how to configure the module. I tried to find some tutorials or user manuals but I couldn't. I installed and enabled the module end I can change the permissions in the /admin/people/permissions page. I want to allow permission to a specific user role to Edit own block content.

How can I give the block ownership to a specific user role?

# Answer
This module is an administrative level module. You can use it to configure who can create/administer/view/etc blocks. For instance, what I did to realize what the module does, logged in as admin:

1. Install and enable the module Block Access
2. Create a new role, lets say testadmin, and grant to it every permission
3. Create a new user, lets say testuser, with that role
4. Log in with user testuser and create a dummy block
5. Log in again as admin
6. Edit the permissions of the role testadmin and deselect the permissions "Administer block access settings" and "Create blocks", under the section "Block Access" (these permissions are added by the Block Access module)
7. Log in again as testuser and try to create another dummy block
8. End of the exercise, because now the user testuser can't create blocks...

In this exercise I only used two permissions, but the module Block Access implements a lot more!
> 2 votes

---
Tags: blocks
---


title: Override field value in view?

text:
# Question
Title: Override field value in view?
I have a content type for events. There is an optional field where the user can provide a link that overrides the default link to the event.

For all of our internal events, the link should take website users to the node of the event. However, for events that are held elsewhere by third parties, the link should take the website user to whatever external link is official for that event.

I'm having difficulty creating a single link field in a view that is the value of the external link, unless there no value, in which case it falls back to the node link.

I can make a re-written field that is `[override_link][path]`, but that always shows the path, no matter what. I only want the path when there is no override\_link value.

This is in a Drupal 7 site.

# Answer
The easiest way IMO to do this is to use the views field template. Here is a very detailed and helpful tutorial on DO. You can find the field template's name in the views theming tab under the advanced tab.

In terms of implementation for your use-case, the field's $output in the template would be empty if there is no link, and then you can change $output to be the link to that node (which you should be able to access with $row-\>nid).
> 1 votes

# Answer
I don't think this is the best solution, so becarefull. I always use Views PHP. This module adds a "Global PHP field" in the views fields, where yo can use PHP to return the value that you need. In this Global PHP field, you will have access to data of others fields as an array in $data variable.

Check this.

Hope this help.
> -1 votes

---
Tags: 7, views
---


title: How are field tables named?

text:
# Question
Title: How are field tables named?
I am looking at my Drupal 7 database, and I think that I see the following pattern:

* Fields that are defined programmatically are stored in tables named field\_data\_fieldname
* Fields that are defined via the UI are named field\_data\_field\_fieldname.

I don't find this convention documented anywhere. Did I take it right?

# Answer
> 1 votes
* Any field created with the core Field UI module has its name prefixed with `field_`.
* Any field created programmatically is named exactly as the module creating it wishes, without the prefix.
* The field data tables are named directly from the field names

Yes, you have it absolutely right.

It's worth noting that the data is also stored in field\_revision\_foo, regardless of whether you're using revisions or not. The field\_data\_foo tables will always contain the most up-to-date data whether revisions are enabled or not.

# Answer
> 0 votes
The table name is always `field_data_<machine_name_of_the_field>`.

It just happens that the Field UI module adds *field\_* as part of the machine name, which is derived from the field name entered in the UI. So, if you create a *Birthday* field, the Field UI module will use *field\_birthday* as machine name of the field, and Drupal will use field\_data\_field\_birthday as database table name.

---
Tags: entities, database
---


# Question
Title: How to display an image when hovering over its title in a View?
In my style sheet (which does seem to be loaded), I have

```
.snhover_img a { position:relative; }
.snhover_img a span { position:absolute; display:none; z-index:99; }
.snhover_img a:hover span {
    display: block;
    width: 350px;
}

```

And in the Title field of my View, I have Rewrite results as

```
<div class="snhover_img">
      <a href="#">{{ title }}<span><img src="/stelnews{{ field_issue_png }}"  /></span></a>
</div>

```

But I always see both the title and the image. Nothing happens on hover. The debugger shows. What am I doing wrong?

**Note**: I am thinking that the style sheet is not really loading. If not, how do I fix that?

# Answer
I post as answer because I have not reach 50 reputation to post as comment. When you debug `.snhover_img a span` is the style `{ position:absolute; display:none; z-index:99; }` applied?
> 0 votes

---
Tags: views
---


title: Node listings on taxonomy term page

text:
# Question
Title: Node listings on taxonomy term page
How to disable/remove node listings on taxonomy term page in Drupal 8?

# Answer
> 0 votes
```
function THEME_NAME_theme_suggestions_page_alter(&$suggestions, &$vars) {
            if (\Drupal::routeMatch()->getRouteName() == 'entity.taxonomy_term.canonical' && $tid = \Drupal::routeMatch()->getRawParameter('taxonomy_term')) {
              $term = Drupal\taxonomy\Entity\Term::load($tid);
              $suggestions[] = 'page__taxonomy__' . $term->getVocabularyId();
            }
          }

```

Create template file "page--taxonomy--VOCABULARYNAME.html.twig" in template folder and you can customize the page with the help of template file.

---
Tags: taxonomy-terms, theming
---


# Question
Title: Change language of a JS element when language has been changed from Drupal language switcher?
First of all, sorry for the really confusing title, but I have no idea how to make it more reader friendly. On my website, there are three languages: English, Finnish and Swedish. The user can change between these languages from the default Drupal language switcher. Now the key part of the website comes from an API that I think is in JS. That JS element has its own language changing parameter.

> src="//www.websiteofapi.com/alpportal/oa\_head.js?proj=api-of-our-company&key=api-key-goes-here&lang=sv&leaflet\_gshim=1"\>

So in order to change the language of the JS element I would need to change that "lang=" part to what language I want. I have that script with the address to the API in my page.html.twig file to make the API call to work all across the site.

Is there a way to change the lang=sv to lang=en and lang=fi when the user changes the language through Druapl language switcher?

From the companys API support they said:

> you have different pages for different languages: website.fi/drupal/ (englisch) website.fi/drupal/sv website.fi/drupal/fi This means that you should have a different script tag for each of these paths. I guess Drupal allows that with help of a language variable that is accessible in your page template. (But I really know little about Drupal, so that's just a guess)

I am sorry for a long and confusing post, but it is really crucial to get this to work and I am losing my mind. PS! I am really new to Drupal.

# Answer
Something like this is what you're looking for I think.

```
theme_js_alter($js) {
  $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
  foreach ($js as $key => $value) {
    if (strpos($value['data'], 'www.websiteofapi.com/alpportal/oa_head.js') !== 0) {
      $value['data'] = "//www.websiteofapi.com/alpportal/oa_head.js?proj=api-of-our-company&key=api-key-goes-here&lang=$language&leaflet_gshim=1"
    }
  }
}

```

Also see Get current language in template
> 0 votes

---
Tags: 8, javascript, i18n-l10n
---


title: Taxonomy term not getting invalidated

text:
# Question
Title: Taxonomy term not getting invalidated
I'm learning the new caching system. For testing purposes I have turned off Page Cache and Dynamic Page Cache.

I've set a custom block with the following:

```
<some code>
$build_array = $view_builder->view($referenced_entity, self::VIEW_MODE, self::LANG_CODE);

$build_array['#cache']['contexts'][] = "route";
$build_array['#cache']['keys'] = ['mymodule_panels_blocks','taxonomy_term', $term->id()];

```

This is for displaying an eck entity with an image that is attached to a taxonomy term.

The expected behavior is that when I point the term to a different eck entity, the taxonomy term is invalidated.

When I check the full list of tags (using http.response.debug\_cacheability\_headers: true) I see my taxonomy term listed (taxonomy\_term:209).

So it would seem I'm all set up. Yet when I change the eck entity to a new one, click Save, then click View, I see the old image still.

When I flush the render cache, I see my new image.

Isn't the invalidation of the taxonomy term automatic when the term is saved? Or do I have to write a hook to invalidate the taxonomy term when it changes?

# Answer
> 3 votes
Yes, the invalidation is automatic. From the debugging you have done so far you only know that the tag is somewhere on the page, but you don't know where it is and obviously it is not where you want it to be. Look in the database table `cache_render`. Clear the cache, so that it is emptied. Now request the page with the block and check for all cached elements the column `tags`.

By the way, you don't need to set cache keys on a block, because blocks do this automatically and for the problem here it's confusing, because the taxonomy id you set in the keys is not invalidated.

---
Tags: 8, caching
---


title: How to use token of Hybridauth?

text:
# Question
Title: How to use token of Hybridauth?
I want to display users' profile data from Hybridauth, so I used "Token Filter" to get the token codes (something like \[hybridauth:firstName\] ), then I put token\_replace in 'user-profile.tpl.php':

```
print token_replace('[hybridauth:provider]', array('hybridauth', $hybridauth));

```

But Drupal give me an error message:

```
Notice: Undefined variable: hybridauth in include() (line 41 of /var/www/html/sites/all/themes/mytheme/templates/user-profile.tpl.php).

```

Anyone have any idea about this?

# Answer
> 0 votes
@Jia-Jun Xu In drupal8 To replace global token type

```
print_r(\Drupal::service('token')->replace($data));

```

Here,$data contains the data from where you have to replace the token.

And if you want to replace a custom token.Then first define it in .module file and then replace IT.

```
use Drupal\Core\Render\BubbleableMetadata;

```

to replace \[node:expirydate\] from the data

```
print_r(\Drupal::service('token')->replace($data,array('node' => ' ')));

```

Here $data contains data from where token has to be replaced and 'node' is token type.For more information visit on below link How to programmatically create a custom token in a module https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Utility%21Token.php/function/Token%3A%3Areplace/8.2.x Hope it will be useful to you.

---
Tags: authentication-authorization, tokens
---


title: How do handle exceptions?

text:
# Question
Title: How do handle exceptions?
I have a service provider that does stuff(for lack of a better word).

Several functions in that service provider deal with a custom table in the database. Lets assume that in a function an `id` is passed, if said `id` doesn't exist I want to stop the process. Throwing out an exception would normally be the way to go, because this is an exceptional situation. The process cannot continue without that information.

I'm not exactly sure how to handle that in Drupal. I don't have that much experience with it.

I noticed that Symfony has an exception handler itself but I'm sure Drupal handles things differently.

Do I log the exception and kill the process? Just throw it out and hope for the best?

# Answer
**Exception handling in Drupal**

Exceptions are handled by FinalExceptionSubscriber, unless there is a more specific exception subscriber handling it before.

Core defines several of them, which are listed here: 27 uses of GetResponseForExceptionEvent

---

**How default exceptions are handled**

When you throw an exception in code

```
throw new \exception('ID ' . $id . ' not found in table xyz!');

```

the default exception handler returns a 500 http status code with this standard message:

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

If you enable error reporting *(admin/config/development/logging)* you get a more verbose exception message displayed on screen:

> The website encountered an unexpected error. Please try again later.
>
> Exception: ID abc not found in table xyz! in Drupal\mymodule... (line 123 of modules/custom/mymodule/src/....php).

---

**Conclusion**

Now, what you want to do depends on how much information you want to disclose to the public. Often if you don't find the data you are looking for a 404 exception is more meaningful than a 500 exception. If none of the core exception handling fits your purpose you can implement a custom exception subscriber:

Handle database connection exception via custom handler
> 11 votes

---
Tags: 8
---


# Question
Title: Core jQuery not working in Bootstrap theme
I am using Bootstrap 3 subtheme and Drupal 8. For some reason when I add the dependency core/jquery it does not work. What am I doing wrong?

```
mysubtheme:
  css:
    theme:
      css/slippry.css: {}
    header: true
    js:
      js/slippry.js: {}
  dependencies:
      - core/jquery

```

The only way I can get jquery to load is when I put the jquery.min.js URL into my page.html.twig file.

# Answer
> 1 votes
Yaml is heavily indentation oriented.

There are yaml validators like: YAMLlint. It will also the intendation for you. But not the wrongly set header option.

You have two indents (spaces) to much before the dash, plus js: needs to be upped too. Also the header property is set wrong, check the docs \- if you want the js in the header, it needs its own library definition:

```
mysubtheme:
  css:
    theme:
      css/slippry.css: {}
  js:
    js/slippry.js: {}
  dependencies:
    - core/jquery

```

> This will work ! (but is in the footer)

This is how the two library definitions will look like:

```
slippry-css:
  css:
    theme:
      css/slippry.css: {}

```

and

```
slippry-js:
  header: true
  js:
    js/slippry.js: {}
  dependencies:
    - core/jquery

```

**You'll need then to add both libraries!**

Maybe this will work too:

```
mysubtheme:
  header: true
  css:
    theme:
      css/slippry.css: {}
  js:
    js/slippry.js: {}
  dependencies:
    - core/jquery

```

To debug your libraries, use libraries\_ui

---
Tags: 8, javascript, bootstrap-theme
---


# Question
Title: Change order of markup for exposed views filter
I have a search box on my homepage, and to style it correctly I need the button to come before the text box in the markup. The current block code looks like the following.

```
<form action="/drupal-7.22/search" method="get" id="views-exposed-form-commerce-search-page" accept-charset="UTF-8"><div><div class="views-exposed-form">
  <div class="views-exposed-widgets clearfix">
          <div id="edit-search-api-views-fulltext-wrapper" class="views-exposed-widget views-widget-filter-search_api_views_fulltext">
                  <label for="edit-search-api-views-fulltext">
            Search for products          </label>
                        <div class="views-widget">
          <div class="form-item form-type-textfield form-item-search-api-views-fulltext">
 <input type="text" id="edit-search-api-views-fulltext" name="search_api_views_fulltext" value="" size="30" maxlength="128" class="form-text required error">
</div>
        </div>
              </div>
                    <div class="views-exposed-widget views-submit-button">
      <input type="submit" id="edit-submit-commerce-search" name="" value="Go!" class="form-submit">    </div>
      </div>
</div>
</div></form>

```

I've looked at `hook_form_alter()` and a few template files, but I think that's the wrong way to do it and I'm far from an expert.

I wouldn't mind being able to clean up that tangle of divs too!

# Answer
> 1 votes
After setting up a test environment and doing some digging, `#weight` isn't going to do you any good. This is what I did to move the button:

Create a new document in your theme folder and name it `views-exposed-form--commerce-search-page.tpl.php`. Now, copy the contents of `sites/all/modules/views/theme/views-exposed-form.tpl.php` to your new file. Next find

```
<div class="views-exposed-widget views-submit-button">
  <?php print $button; ?>
</div>

```

And move it wherever you please, for my test I moved it directly below:

```
<div class="views-exposed-widgets clearfix">

```

which made it the first item in the form. Finally, clear the cache and reload the page.

Further, you should look into the Theme Developer module if you're not using it already. It is very handy for figuring out which `.tpl.php` file you should create, or which `_preprocess()` function should be used, to effect the element you're targeting.

# Answer
> 1 votes
You can create your own views-exposed-form.tpl.php file and move the submit button to the top, or add a class to it and use css to float left and right. This however would affect all exposed filter on your site.

If you want to alter the form you should use the function

```
function MODULENAME_form_views_exposed_form_alter(&$form, $form_state)

```

Your best option is however to try manipulating it with css.

# Answer
> 0 votes
You have add them in

$form\['#info'\]\['filter-byline-names'\]\['value'\] = 'abc'; $form\['#info'\]\['filter-byline-profile-type'\]\['value'\] = 'efg';

where **abc**, **efg** are the newly added form element

```
$form['abc'] = array(
        '#type' => 'textfield' ,
        '#title' => 'ABC' ,
      );
      $form['efg'] = array(
        '#type' => 'select' ,
        '#title' => 'Profile Type',
        '#options' => array('asdasd','rajveer','gangwar'),
      );

```

---
Tags: views, forms
---


# Question
Title: Edit button on the top right menu disappeared, how can I get it back?
Put my website in development mode in the past but I'm having a hard time finding the setting to re-enable the in field editing of nodes.

Which configuration setting is responsible for toggling the edit button in the top right corner and the pencil icon on blocks and content?

Edit:

I found out there are many javascript errors, check the screenshot here.

# Answer
The issue was caused because of an unclosed div tag in multiple blocks on my site. If you have this issue check all related twig templates, blocks and content for unclosed HTML tags.
> 0 votes

---
Tags: 8
---


# Question
Title: Show specific field(s) from created content-type
Question might be easy, but I have a problem. I created a content-type (page), made it as a block with Node Block module, put this block in content. But it prints all stuff: title, authored by, date and so on. But what I nead is to print only body. But there might be another case, when I want to print also a title.

So the question is in general, how to print fields that I want from content-type, maybe there is a module for this or a more convenient way.

I'm using latest Drupal 7.

Thanks!

# Answer
You can configure this as a per content type level, not for each node in particular.

Edit the content type, go to *Node Block settings* and under *Default view mode* select a convenient value. Then, click on *Manage presentation* tab and select the same value you set previously under *Default view mode*, and finally configure the fields and positions you want to be rendered.
> 0 votes

---
Tags: views, nodes, entities, blocks
---


title: Adding logic to a page

text:
# Question
Title: Adding logic to a page
I am new to Drupal, and I am trying to add some behavior to an existing page within Drupal.

Using the admin UI, I created an model with 2 numbers (num1, num2). I then rendered it into a form.

Now I would like to add a third field, and compute using the client the sum of num1 and num2 into this new field. This needs to be done as you type the numbers.

I wanted to use Javascript to do this, but I really don't know where to start. Is there an example on how to simply add some logic into an exiting screen that is generated by the admin tools?

This is more information.

Then, I just add these to fields into a page like so:

Again, at this point I would like to just add the sum of both numbers into a 3ed field that is not there yet (of course my project is much more complex, but this is a simple example). So I was going to add field\_number3 into my Content type, and I wanted to do some simple Javascript to calculate the field.

I could really use some step by step examples, to just to know where to place a module, and what code to type in the module to only add this behavior to my content.

I am very new to Drupal, and I am using Drupal 8.

# Answer
> 3 votes
Attaching custom JS to form

Adding css and javascript to a drupal 8 module

Here's an example of using `hook_form_FORM_ID_alter`. For this you'll need to make a custom module (conveniently named custommodule in the example below).

# Module directory:

```
custommodule/
|- js/
   |-- custommodule.js
|-- custommodule.info.yml
|-- custommodule.libraries.yml
|-- custommodule.module

```

# File contents:

* custommodule.info.yml

```
type: module
name: Custommodule
description: 'Custom stuff'
package: Custom
core: '8.x'

```
* custommodule.libraries.yml

```
custommodule:
  version: 1.x
  js:
    js/custommodule.js: {}
  dependencies:
    - core/jquery

```
* custommodule.module

```
<?php

use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_FORM_ID_alter().
 */
function custommodule_form_node_article_edit_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $form['#attached']['library'][] = 'custommodule/custommodule';
}

```
* custommodule.js

```
(function($) {

  Drupal.behaviors.myBehavior = {
    attach: function (context, settings) {

      var num1 = $("#edit-field-num-1-0-value").value;
      var num2 = $("#edit-field-num-2-0-value").value;
      var result = (Number(num1)+Number(num2));
      $("#edit-field-num-3-0-value").value = result;
    }
  };

})(jQuery);

```

The example uses the default article node type, with 3 integer fields (field\_num\_1, field\_num\_2, field\_num\_3), and works on the article edit form (form id -\> node\_article\_edit\_form). The js part is also very basic so all it does is set the third field value once the page loads. `Drupal_add_js` is deprecated, so we use the $form\['#attached'\]\['library'\] array to attach a library (defined in the custommodule.libraries.yml file) that contains the JS file (a single libraries.yml file can define more libraries, which can include more js/css files).

# Answer
> 1 votes
This question is very broad and should be easy to find answers to, but if you're new to Drupal I understand it can be hard to know where to look. You'll need to implement hook\_form\_alter or hook\_form\_FORM\_ID\_alter in a custom module to be able to add your JS via drupal\_add\_js:

```
MODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'NAME') {
    drupal_add_js(PATH);
  }
}

```

You will then need to look at Managing JavaScript in Drupal 7 in order to work out how to actually code the JavaScript you need.

---
Tags: javascript, hooks
---


# Question
Title: how to duplicate a form action programatically
when a form action takes place, it posts the fields and also redirects to that page, right? I need to make a custom form do the same, I have successfully made it post the fields in my drupal 8 custom module , using an http request with guzzle, but how do i make it redirect simultaneously as well?

# Answer
In your submit handler:

```
$form_state->setRedirect($route_name, $parameters, $options);

```

Or if you have a URL object:

```
$form_state->setRedirectUrl($url);

```

Reference:
> 1 votes

---
Tags: 8, forms
---


# Question
Title: How to get all the content types that don't have nodes?
In Drupal 7 if you want a list with the content types that don't have nodes you can do it with the following query:

```
SELECT type, name, COUNT(nid) as total
              FROM node_type LEFT JOIN node USING(type)
              GROUP BY type
              HAVING total = 0
              ORDER BY name

```

But in Drupal 8 we don't have the {node\_type} table and you can't have access to all the available content types unless you use the 'entity.manager' service or you go to look inside the {config} table that have a column named name, but in the name column you will find this:

```
node.type.CONTENT_TYPE_MACHINE_NAME1
node.type.CONTENT_TYPE_MACHINE_NAME2

```

There is not an easy way to get the information from this table.

I found an example in the Entity Query support for aggregated queries page:

> Let's assume you want the amount of nodes per node type.
>
> ```
> $query = Drupal::entityQueryAggregate('node');
>
> $result = $query
>   ->groupBy('type')
>   ->aggregate('nid', 'COUNT')
>   ->execute();
>
> ```

But only works for content types with more than 1 node, why? Again there is not way to find content types in the database that don't have nodes.

I really don't know the reason for this missing important part (and I can't find it) but I think that this is very important because the only way now to obtain the content type label is through the 'entity.manager' service.

In short, how to get all the content types that don't have nodes?

# Answer
> 3 votes
I know that you can use the 'entity.manager' service to get all the available content types and then through a loop look for all the nodes for each content types. But this way is very long and involve many database queries.

This is the short way that I found to obtain this information:

```
// Getting the database connection.
$connection = \Drupal::service('database');
$query_content_types = "SELECT DISTINCT SUBSTR(name, 11) as type FROM config WHERE name LIKE 'node.type.%'";
// Creating a temporary table.
$content_types_temporary_table_name = $connection->queryTemporary($query_content_types);

$query = "SELECT node_type.type, COUNT(nid) AS total
          FROM $content_types_temporary_table_name node_type LEFT JOIN {node} USING(type)
          GROUP BY type
          HAVING COUNT(nid) = 0
          ORDER BY type ASC";

$result = $connection->query($query);
dpm($result->fetchCol('type'));

```

---
Tags: 8, nodes, database
---


# Question
Title: Add a CSS basing on the author of the comment
This node has a comment by the user #1, who is the node author, and a comment by an anonymous user. I want to add an extra CSS class to comments by the node author.

The variables in Bartik's comment.tpl.php include `$author` and `$comment-by-node-author`.

What is the correct syntax for an if statement saying if this comment is by the node author (or by user #1) apply the class *example* and just print the comment as usual when the author is somebody else?

# Answer
Drupal applies a CSS class to comments created from the user who is the author of the node (comment-by-node-author), but since you want to add a custom CSS class when the user who created the comment is either the node author or the user #1, I would use the following code.

```
function mytheme_preprocess_comment(&$variables) {
  if (($variables['comment']->uid == $variables['node']->uid) || $variables['comment']->uid == 1) {
    $variables['classes_array'][] = 'example';
  }
}

```

Using that code in your theme, the comment will have your custom CSS class when the user who created the comment is the same user who created the node, or when the user who created the comment is the user #1.
> 2 votes

# Answer
If (what I'm not sure) understand your question correctly, you want to add an extra class if the comment was posted by the node author.

**As explained in Bartik documentation:**

> ```
>  /*   - $classes: String of classes that can be used to style contextually through
>   *   CSS. It can be manipulated through the variable $classes_array from
>   *   preprocess functions. The default values can be one or more of the following:
>   *   - comment: The current template type, i.e., "theming hook".
>   *   - comment-by-anonymous: Comment by an unregistered user.
>   *   - comment-by-node-author: Comment by the author of the parent node.
>   */
>
> ```

There are already specific classes for comments posted :

* by node author : `.comment-by-node-author`
* by anonymous : `.comment-by-anonymous`

And you can see that in your node markup :

```
<div class="comment comment-by-node-author clearfix" about="/comment/2#comment-2" typeof="sioc:Post sioct:Comment">

/* ... */

<div class="comment comment-by-anonymous clearfix" about="/comment/3#comment-3" typeof="sioc:Post sioct:Comment">

```
> 2 votes

---
Tags: theming, comments
---


title: Pre-processing a field in a views table

text:
# Question
Title: Pre-processing a field in a views table
Right out front, I am working with Drupal 8.3.1.

I have a view that uses the table output format. One of the fields it outputs is a multi-value date field in the content type. It takes all the dates and puts them into an `<ul>` element that it then renders in the table cell.

I want to be able to preprocess that date field, to assign classnames to the individual `<li>` elements in it. I've tried to use `template_preprocess_views_view_field`, but by the time that fires, the list has been built and rendered to HTML and is presented as a `#markup` value.

I've looked at various other preprocess hooks and none of them seem to be able to let me hook in and do this. Is this a limitation of Views? Or am I missing something.

# Answer
> 0 votes
In the settings of the view field you can use this option (located in STYLE SETTINGS):

> \[x\] Use field template

Now the field is rendered by the same field template you use in the content type including preprocess hooks.

To see the added theme hook and field template enable Twig debug and look at the html source in the browser.

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


title: Attach WYSIWYG to Drupal Form

text:
# Question
Title: Attach WYSIWYG to Drupal Form
With a custom Drupal form, how can you attach WYSIWYG functionality to a textarea with the WYSIWYG module?

# Answer
> 2 votes
review this indication to Drupal 7 (with a little indication to drupal 6) http://drupal.org/node/1031160. specifically is about how to display an editor inside textarea in drupal 7, so I guess that could be useful to start (seems that the last comment have a tested way).

may be could be an alternative to do this instead/with WYSIWYG.

# Answer
> 9 votes
The wysiwyg module is tied to the input format system.

Use `'#type' => 'text_format'` when defining your text area.

# Answer
> 7 votes
You should use type = 'text\_format' instead of text area. and format = 'editor\_format'. The code will look like this.

```
$form['description'] = array(
  '#type' => 'text_format',
  '#title' => t('Description'),
  '#format' => 'full_html' //the format used for editor.
);

```

# Answer
> 4 votes
Here is mine:

```
$form['my_module_my_form_my_field'] = array(
  '#type' => 'text_format',
  '#title' => t('Awesome title'),
  '#format' => isset($edit['format']) ? $edit['format'] : NULL,
  '#base_type' => 'textarea',
  '#default_value' => variable_get('my_module_my_form_my_field', '')['value'],
  '#description' => t("Awesome description."),
  '#required' => FALSE,
  '#maxlength' => 500,
);

```

I had to add the `['value']` to the `#default_value` cause it wasn't being loaded after saved.

7x Form API Reference

# Answer
> 0 votes
The WYSIWYG module is only a way to use one of the many wysiwyg editors out there. Once you install the wysiwyg module (http://drupal.org/project/wysiwyg), go to the configuration for the module (admin/config/content/wysiwyg). There will be installation instructions for many Wysiwyg editors available. For example, for FCKeditor, it says the following:

> Extract the archive and copy its contents into a new folder in the following location: sites/all/libraries/fckeditor
>
> So the actual library can be found at: sites/all/libraries/fckeditor/fckeditor.js

So, download the editor, extract the archive to the given directory. Once you do this (assuming you've done it correctly), you will be able to change the editor for given input formats on the Wysiwyg config screen. You will then need to assign different operations for each type (filtered HTML, full HTML, etc.). Click "Edit" under operations within the admin/config/content/wysiwyg in the row for whichever input format you're interested in. From here, check which buttons you want.

# Answer
> 0 votes
It doesn't seem it is possible with Wysiwyg version 7.x-2, but the form builder for the profile settings uses the following array:

```
  $profile['settings'] += array(
    'default' => TRUE,
    'user_choose' => FALSE,
    'show_toggle' => TRUE,
    'theme' => 'advanced',
    'language' => 'en',
    'access' => 1,
    'access_pages' => "node/*\nuser/*\ncomment/*",
    'buttons' => array(),
    'toolbar_loc' => 'top',
    'toolbar_align' => 'left',
    // ...
  );

```

The "access\_pages" array index would allow to set for which pages the editor is shown, but the module doesn't provide any form field to change that code, nor does any function uses that value.

It could be that value was used in previous versions, and the code to handle it is still being ported, or that option is being introduced within the next versions of the module.

---
Tags: 7, forms, wysiwyg
---


# Question
Title: How to suppress print in only in front page via twig
`{{ node.field_test1.entity.label }}` prints the label of a taxonomy field in a node.html.twig. Is there a possiblity to suppress that outside the frontpage via node.html.twig? Or enable that only for front\_page? That means: in a view, that is searching for this term exactly, I have the same information double on screen in the view result.

"is\_front"condition is not defined in node.html.twig. 'EDIT: What I meant is that:

```
{% if not page %}
      <h2{{ title_attributes.addClass('node__title') }}>
        <a href="{{ url }}" rel="bookmark">{{ node.field_kategorie.entity.label }}: {{ label }}</a>
      </h2>
    {% endif %}

```

This'll be printed all over. How to do: print this (in the URL above) only for front page, for example not not in a view (that just searched for this entity)?

# Answer
> 0 votes
You can have as many differen view modes as you want, both the frontpage and the term pages by default are views, so they are easy to customize.

So create a new one under Admin \> Structure \> Display modes, then enable it for that node type and configure the fields as you want. Then change one of the views to use that view mode.

Another option would be logic in process, but then you need to add the right cache context.

Or you just hide that field with CSS.

---
Tags: theming, 8
---


# Question
Title: How to add a custom Save & <do some action> button to Node Add/Edit form?
I added the following code in hook\_form\_alter() and I get my button on the Add/Edit node form:

```
$form['actions']['save_add_lesson'] = array(
  '#type' => 'submit',
  '#value' => 'Save & Add a Lesson',
  '#name' => 'op',
  '#submit' => array('mymodule_node_form_submit'), /* NEED this */
  '#weight' => 1000
);

```

But, clicking the button doesn't seem to hit hook\_node\_submit() or hook\_node\_insert(). I'm assuming I'm missing a hook or something in the button creation...anyone have any ideas?

---

Then added this function:

```
function mymodule_node_form_submit($form, &$form_state) {
  // Do stuff before saving the node

  // Call this to save the node
  node_form_submit($form, $form_state);

  // Do stuff after saving the node
}

```

# Answer
> 7 votes
Got it :D

Adding

```
'#submit' => array('mymodule_course_form_submit'),

```

To the submit button worked. Like this:

```
$form['actions']['save_add_lesson'] = array(
  '#type' => 'submit',
  '#value' => 'Save & Create a Lesson',
  '#name' => 'op',
  '#submit' => array('mymodule_course_form_submit'),
  '#redirect' => 'node/add/lesson',
  '#weight' => 1000
);

function mymodule_course_form_submit($form, &$form_state) {
    $nid = mymodule_node_save_no_redirect($form, $form_state);

    $form_state['redirect'] = 'node/add/lesson';
    unset($_GET['destination']);
    drupal_static_reset('drupal_get_destination');

    if($nid != -1) {
        $_SESSION['mymodule_course_nid'] = $nid;
        drupal_redirect_form($form_state);
    } else {
        // Failed to save Course...notify user
        drupal_set_message('Failed to save Course Content', 'error');
    }
}

```

# Answer
> 0 votes
There is also a good Content Type: Extras module for that + many more options:

* Set default values for common content type settings (see below) - you can still override the defaults per content type

'Save and New' button to add new nodes of the same type right after saving

'Save and Edit' button to save a node and continue working on it (great for long posts so you don't have to worry about losing all of your information).

User permissions for content type duplicated on content type add/edit page

Sets a maximum length (26 characters) for 'Add new field' and 'Add new group' (if field\_group module is enabled) machine names to prevent submitting the form and getting an error message

Add a 'Save' button to the top of the 'manage fields' form

Auto-populate new field machine name, new group machine name, and existing field label on manage field forms

Add a 'Cancel' button to node edit forms

Ability to set node title visibility when viewing node

Ability to hide title of front page (takes precedence over content type setting)

Ability to add form submission buttons to top of 'Manage fields' content type forms and/or node edit forms.

Ability to remove body field on content type creation.

Ability to set description field in content type edit form to required.

Set defaults for:

* Title field Preview button

'Save and New' button (with configurable text)

'Save and Edit' button (with configurable text)

Published

Promoted to front page

Sticky at top of lists

Create new revision

Display author and date information

User permissions

Node title visibility per content type

# Answer
> 0 votes
The following code worked for me to add a second button on a form that saves and creates another item, instead of going straight to see the new node.

```
function MYMODULE_MYFORMID_form_alter(&$form, &$form_state, $form_id){
  $form['actions']['submit2'] = array(
    '#type' => 'submit',
    '#value' => t('Save & Create Another Item'),
    '#access' => TRUE,
    '#submit' => array('MYMODULE_node_form_submit'),
    '#redirect' => 'node/add/new-node-item',
    '#weight' => -30,
  );
}

function MYMODULE_node_form_submit($form, &$form_state) {
 if ($form_state['nid']) {
   $form_state['#redirect'] = 'node/add/new-node-item';
 }
}

```

See https://www.drupal.org/node/290462.

---
Tags: forms
---


# Question
Title: Why are there .htaccess and php files in ./sites/default/php/twig
Just wondering, it may be related to cache settings, but why are there lots of php and .htaccess files in the public:// dir?

# Answer
The PHP files are compiled Twig templates and the .htaccess file protects them from public access. You can switch off the caching of compiled twig templates by setting this service parameter to `FALSE`.

```
# Twig cache:
#
# By default, Twig templates will be compiled and stored in the filesystem
# to increase performance. Disabling the Twig cache will recompile the
# templates from source each time they are used. In most cases the
# auto_reload setting above should be enabled rather than disabling the
# Twig cache.
#
# Not recommended in production environments
# @default true
cache: true

```

You find this in sites/default/default.services.yml, which you have to rename to sites/default/services.yml to activate it.
> 3 votes

---
Tags: 8, files, .htaccess
---


# Question
Title: How to include js library from /sites/all/libraries in twig template with attach_library?
According to https://sqndr.github.io/d8-theming-guide/libraries/libraries-and-twig.html, you can include a library within twig template to only load it on specific pages using `{{ attach_library('theme/library') }}`. This appears to be for libraries included in mytheme.libraries.yml.

Is there a way to use this to include a library from sites/all/libraries? It seems silly to add a library to my theme folder when it is already available globally.

# Answer
There was likely a module that required the files in question to be added to the sites/all/libraries folder. You could review that module on how it adds those files as libraries. Check that module for a .libraries.yml file or check to see if the module implements hook\_library\_info\_build(). Once you know the how to reference the library, you should be able to use the same reference in your twig template.

As an example, the Easychart module (https://www.drupal.org/project/easychart) has both a .libraries.yml and implements the hook in it's .module file. To reference one of those libraries you would use "easychart/easychart.render" or "easychart/lib.highcharts"
> 1 votes

---
Tags: 8, theming
---


# Question
Title: Pre-select Group Audience for Organic Groups
Here is my situation.

I am using the latest version of Organic Groups on Drupal 7. Every user on my site is part of one group and one group only. Is there a way to make it so that when users are creating group content, the group they belong to is automatically pre-selected? Again, every user is only in one group (but there are numerous groups), so it's superfluous to force them to make a group selection whenever they are creating group content.

# Answer
> 0 votes
1. You can use Field Permission module to not allow a user to see the group field on content type.
2. Use hook\_form\_BASE\_FORM\_ID\_alter() to set a default field value for group field based on current logged in user.

as a sample code (not tested)

```
function mymodule_form_node_form_alter(&$form, &$form_state) {
  $node = $form_state['node'];
  if (!isset($node->nid) || isset($node->is_new)) {
    global $user;
    $groups = og_get_groups_by_user($user);
      if(is_array($groups)) {
      // This needs to be evaluated to check proper mapping of what field expect to set a default default field value
      $form['group_field_name']['#default'] = $groups[0];
      }
  }
}

```

# Answer
> 0 votes
Entity Reference Prepopulate is the best way to do this without custom code like arpitr described. You would rewrite the links to look like

```
/node/add/article?og_group_ref=123

```

These links could be on the group's page or you may find a token to populate the gid automatically based on user.

---
Tags: users, organic-groups
---


# Question
Title: Install module that requires composer on server with only FTP
I am working on website that only has restricted ftp access. Ya, no way around it.

I want to install the module PHPmailer, which uses composer to install libraries.

I have a local composer run dev site, from which I installed properly, then moved the module dir, and `composer.json`, `composer.lock` to the server, but when installing the module on the server I get the error

`Please install the PHPMailer library by executing 'composer update' in your site's root directory. (Currently using PHPMailer library version Missing)`.

Does composer update the database or what is going on here?

How can I easily install a module that made it self dependant on composer?

# Answer
> 4 votes
That error message is called from the modules install file. It's checking to see if the PHPMailer class exists, and if not, let's you know the library needs to be installed before you can install the module.

If you successfully installed the module on your local dev site, then Composer downloaded the PHPMailer library to the root 'vendor' folder. In the 'vendor' folder there should be a 'phpmailer' folder. You just need to copy this folder over to your website's server (to it's root 'vender' folder) and then you should be able to install the module.

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


# Question
Title: Is putting content in the codebase or the database better for performance?
I recently created a website footer using a block template. Some of the footer's content was entered through the block's wysiwyg (stored in the database), but other code-heavy elements were placed in the block template file (stored in code). I've noticed that the footer block loads slow at times. Other times, the content inserted through the wysiwyg loads a few seconds before the content that was inserted in the the block template.

I'm curious, is storing html content in the database better for performance than storing html content in template files?

EDIT: After I posted this, I also realized that the footer is being rendered with Blocks whereas the rest of the page is being render with Panels. I'm not sure if that would have any effects of its performance.

# Answer
Quick answer is that the DB should be slower. In reality the only way to know for sure is to profile the PHP code and get a cache grind of it. One being rendered by panels and the other by core blocks is the main reason most likely in this case.
> 3 votes

---
Tags: 7, theming, database, performance
---


# Question
Title: What does "Prefetch views unpack data" in APDQC module do?
There is an option in the APDQC (Asynchronous Prefetch Database Query Cache) https://www.drupal.org/project/apdqc module for:

**Prefetch views unpack data**

It's unclear what this does. Should this be turned on or left off as default?

# Answer
Really depends on your workload. In some cases having all of the views data prefetched is faster, in other cases it's slower. If you have 50+ views then it's best to leave it off, if you have just a couple views, turning it on is faster.

Side note: I created the patch for creating this cache in views, now I wish it was prefixed by the view name so prefetch would be easier.
> 1 votes

---
Tags: caching, performance
---


# Question
Title: How do I code to take action when a VBO (bulk action) is finished?
I've recently coded a few Drupal\x\Plugin\Action classes that respond nicely to my VBO (now bulk actions?) in Drupal 8. Now I'd like to implement a hook, or whatever is required, to take action when all the entities in a selected action have been processed...essentially a VBO post-process hook like we had with hook\_views\_bulk\_operations\_finish in Drupal 6. **Where and how can I implement that?**

I see no obvious hook in D8 to do this, and unfortunately, I've been unable to get Rules to work in D8 (still really confused by Rules and Actions configuration) so I really don't want to go down that path if I don't have to, yet.

# Answer
> 1 votes
This is how I tackled this scenario in D7.

**In my custom VBO code I did a variable\_set()** and then I use hook\_views\_pre\_render (note that the D8 hook params changed, so don't copy the hook from my code below) and did a variable\_get(), if it was not empty, then do your action.

```
/**
 * Implements hook_views_pre_render().
 */

function bulk_mail_hauliers_auto_emailing_views_pre_render(&$view) {
// check the view name
if ($view->name == 'hauliers_auto_emailing') {

    $store_all_in_one_en = variable_get('bulk_mail_hauliers_auto_emailing_all_in_one_en', 0);

    // check that variable_get is not empty, which means VBO ran.
    if ($store_all_in_one_en != 0) {

      // CUSTOM ACTION GOES HERE

      // delete the variable
      variable_del('bulk_mail_hauliers_auto_emailing_all_in_one_en');

    }

}

```

So you can basically do this in D8, except use the D8 equivalent of variable\_set,get,del.

---
Tags: 8, views, actions
---


title: How to add Block Into View?

text:
# Question
Title: How to add Block Into View?
I want to add a block which is created by a view. This block has slider and I need to put between some fields of view.

How can I do this?

# Answer
> 15 votes
There are a few ways to do this.

The simplest is to add your block view to the header or footer of the new view. To do this, go to the configuration page for the new view and click **Add** next to **Header** or **Footer** (in the middle column). Choose *Global: View area* and then select your view.

Alternately, for maximum control over layout, you can use the Panels module, but it is much harder to set up.

Another option is the Views Field View module. Here is a tutorial about how to set this up.

One further option is the Viewfield module.

# Answer
> 1 votes
You can simply Views Block Module

> This module exposes all available blocks as a views area or field. This way you can add any block inside a field, footer or header in your view.
>
> Blocks that are generated by views can not be selected, these blocks can not be inserted into views. Add a block as an area
>
> ```
> Go to the view that needs a block inside an area
> Click on add next to header, footer or no result behavior
> Select Global: Block area
> Select the block that you want
>
> ```
>
> After saving the view, the block will now be visible in the header or footer. Add a block as a field
>
> ```
> Go to the view that needs a block inside a field
> Click on add next to fields
> Select Global: Block area
> Select the block that you want
>
> ```
>
> After saving the view, the block will now be visible in the view content.

---
Tags: views
---


title: Facet block with dynamic title

text:
# Question
Title: Facet block with dynamic title
Is there a way to dynamically change the facet block title on each page based on the field label of the specific content type? The same field has different labels in each content type.

For example if we have in ‘Content type 1’ a field with Machine name: field\_1 and label ‘AA’ and the same field in ‘Content type 2’ with label ‘BB’ when we are on Content type 1 page the facet block mast show AA and when we are on Content type 2 page it mast show BB.

I found a way to change the title with CSS using the Code per Node module, but it is not automatic and I have to insert the code in each content type. It doesn't seem to be right. There must be a better way.

I use this CSS in each content type.

```
.block-facetapi-”THEBLOCKID” .block-title {
  visibility: hidden;}
.block-facetapi-”THEBLOCKID” .block-title::after {
  content: 'Label B';
  visibility: visible;}

```

# Answer
You could change the block title in your theme or module using the theme function or theme preprocess function.

For example:

```
/**
 * Implements hook_preprocess_facetapi_title
 */
function HOOK_preprocess_facetapi_title(&$variables) {
  $some_condition = TRUE;
  // If some condition
  if ($some_condition) {
    // Some title..
    $title = t('Custom title');
    // Set theme/template variable for title
    $variables['title'] = $title;
  }
}

```

See also: `theme_facetapi_title`
> 1 votes

---
Tags: entities, search
---


title: how to setup entity access correctly?

text:
# Question
Title: how to setup entity access correctly?
How to setup entity access correctly?

i have entity:

```
/**
 * @ContentEntityType(
 *   id = "test_entity",
 *   bla... let me know if you need detail of this
 *     "route_provider" = { "admin" = "Drupal\test_entity\Entity\TestEntityRouteProvider" },
 *   bla... let me know if you need detail of this
 */

```

and `class TestEntityRouteProvider extends AdminHtmlRouteProvider implements EntityRouteProviderInterface` with `getRoutes` as follow:

```
$parameters = ['target_type' => 'test_entity_type', 'target_id' => ['type' => 'entity:{test_entity}']];

$route = (new Route('/admin/testing/my-entity/{test_entity}'))
         ->addDefaults([
           '_controller' => '\Drupal\test_entity\Controller\TestEntityViewController::view',
           '_title_callback' => '\Drupal\test_entity\Controller\TestEntityViewController::title',
         ])
         ->setOption('parameters', $parameters)
         ->setRequirement('_entity_access', 'test_entity.view');

$route_collection->add('entity.test_entity.canonical', $route);

```

i read comments in: EntityAccessCheck:Access, it said:

```
  /**
   * ... dynamic entity type:
   * example.route:
   *   path: foo/{entity_type}/{example}
   *   requirements:
   *     _entity_access: example.delete
   *   options:
   *     parameters:
   *       example:
   *         type: entity:{entity_type}

```

**question**: is my $parameter in class `TestEntityRouteProvider` correct? i'm not sure if i follow the instruction in comment correctly.

and with my code above, `$entity` value in EntityAccessCheck:Access is **"test\_entity-15"** as string

\*for reference: **"test\_entity-15"** is referring to my test entity ID the same as in my url: **/admin/testing/my-entity/test\_entity-15**

```
if ($parameters->has($entity_type)) {
  $entity = $parameters->get($entity_type); // <-- value: "test_entity-15"
  if ($entity instanceof EntityInterface) { // will false in here
    return $entity->access($operation, $account, TRUE); // and didn't reach here
  }
}

```

and will giving me response:

> 403: You are not authorized to access this page.

what am I missing here? let me know if you need my particular part of my code.

Thank You,

# Answer
You say "i have entity and `class TestEntityRouteProvider extends AdminHtmlRouteProvider implements EntityRouteProviderInterface`. Normally you don't rewrite all of the route generating code when extending an entity route provider, you only modify some of the routes, rarely the whole set of routes in `getRoutes()`. But always execute the parent method first. See this example from a core entity type:

```
<?php

namespace Drupal\aggregator;

use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\Routing\AdminHtmlRouteProvider;

/**
 * Provides HTML routes for the feed entity type.
 */
class FeedHtmlRouteProvider extends AdminHtmlRouteProvider {

  /**
   * {@inheritdoc}
   */
  protected function getCanonicalRoute(EntityTypeInterface $entity_type) {
    $route = parent::getCanonicalRoute($entity_type);
    $route->setDefault('_title_controller', '\Drupal\aggregator\Controller\AggregatorController::feedTitle');

    return $route;
  }

  /**
   * {@inheritdoc}
   */
  protected function getEditFormRoute(EntityTypeInterface $entity_type) {
    $route = parent::getEditFormRoute($entity_type);

    $route->setDefault('_title', 'Configure');

    return $route;
  }

}

```

Or if you don't need to modify anything you simply use the standard class for the administration of entity types

```
  *     "route_provider" = {
  *       "html" = "Drupal\Core\Entity\Routing\AdminHtmlRouteProvider",

```

in the entity type annotations. Is it working then?
> 1 votes

---
Tags: 8, entities, routes, users
---


# Question
Title: Display hierarchical entity reference fields inside node
I have the following content types in Drupal 8 :

**User**

* field: image
* other fields

**Organization**

* field: logo
* Entity reference to User \[one to many\]
* other fields

**Event**

* Field: Date
* Field: Description
* Entity reference to Organization \[one to many\]

**The event nodes need to look like this (display the following):**

* Event Title
* Event Date
* Event Description
* All the organization logos (from the organizations added as a reference entity to the event)
* All the user logos that belong to the already referenced organizations

Is there any way to do this with already existing Drupal 8 modules or do I have to write some custom code ?

# Answer
> 1 votes
You could render this with four different display modes:

1.) The Event view mode to start with:

* Event Title
* Event Date
* Event Description
* Reference field for Organization, configured to render the view mode `logos1`
* Reference field for Organization, configured to render the view mode `logos2`

2.) The Organization view mode `logos1` contains one field for the Organization logos:

* Image field logos

3.) The Organization view mode `logos2` contains one field for the User logos

* Reference field for the content type User, configured to render the view mode `userlogos`

4.) The content type User view mode `userlogos`

* Image field for user logos

To implement two instances of the reference field you need the module Display Suite. Or combine logo1 and logos2 in one view mode with two fields, but then the logos will get mixed. Or use for the second reference field a View, with the help of EVA.

---
Tags: 8, entities
---


# Question
Title: How do I install the latest release of Drupal with Composer
Instructions on Drupal.org for installing Drupal with composer provides the following example:

```
composer create-project drupal/drupal my_site_name 8.3.*@dev --no-dev

```

This provides me with the latest DEV version of Drupal. How do I get the lasted stable release?

# Answer
```
composer create-project drupal-composer/drupal-project:8.x-dev \
  YOURDIRNAME \
  --stability dev \
  --no-interaction

```
> 2 votes

---
Tags: composer
---


# Question
Title: What is the proper way to set up an AWS Auto-Scale group?
What is the proper way to setup an EC2 Web Server with the aim of serving a site which experiences high demand once a month via 1 small EC2 for 90% of the time and then enter a load balanced group for the other 10%. I understand the AWS mechanics, AMI, auto scaling, metrics, and load balancer, but I don't know the best practices of setting up a CENTOS server to serve multiple servers.

I was thinking http://tecadmin.net/mount-s3-bucket-centosrhel-ubuntu-using-s3fs/# with S3 buckets (I ran into a few problems), but would a simple mounted volume be better?

I would really appreciate advice from anyone who has used AWS in this way with Drupal. Another article I read is Using a load balancer or reverse proxy.

Obviously, performance is a big consideration. I know S3 is fast, but I imagine it's slower than using a mounted volume.

# Answer
Drupal considerations are similar to WP, Magento and Stateless applications.

* Share your code across your auto scaling group via AWS EFS, Lsyncd, S3 or NFS.
* Use CDN + S3 for static content
* Separate Database (AWS RDS)
* Make sure to use Varnish and NGINX.
* Use Github/BitBucket and define a development workflow system.
* Cache and manage session via Redis/Memcached.

More details: https://www.clickittech.com/cloud-computing/scaling-in-the-cloud/

The above link is an article about the Art of scaling which considers Drupal, WP and Saas Applications.
> 1 votes

---
Tags: 7, files
---