# Question
Title: Validation Errors with Form Element on Node Form
I'm creating a custom field element type that contains other interactive elements. I've been following the Drupal core File module to try to simulate some of the functionality of it. One thing I've been having trouble with is submission and validation errors.

When you upload a file using the File module, only that part of the form seems to be submitted. In my module, the whole form gets submitted instead. I'd really like to have it act like the File module by only submitting my one element and its contained elements.

The other thing is validation errors. In the file module when you run into an error with an uploaded file, the validation error appears within the area where the file field appears instead of the top of the page. I also have the trouble of my validation for that field being checked when I submit the whole form, but I don't want this validation to happen for submitting the whole form. I only want validation when I hit the button within my custom element like file validation works.

Here's what I have so far. I apologize that this is regarding the same code as a previous question, but that was about the overall framework to use and this is specifically asking about issues with submission and validation for this custom element.

```
/**
 * Implements hook_element_info().
 */
function my_module_element_info() {
  $types['user_management'] = array(
      '#input' => TRUE,
      '#process' => array('my_module_user_management_process'),
      '#size' => 45,
  );
  return $types;
}

/**
 * Implements hook_form_FORM_ID_alter().
 */
function my_module_form_my_module_node_form_alter(&$form, &$form_state) {
  $form['administrators_management'] = array(
      '#title' => t('Account Administrators Management'),
      '#type' => 'fieldset',
      '#description' => t('Administration for users who have administrative access to this account.'),
      '#weight' => 33,
  );
  // unset($form['my_module_administrators']);
  $form['administrators_management']['user_management'] = array(
      '#type' => 'user_management',
  );
}

/**
 * Process function to expand the user_management element type.
 */
function my_module_user_management_process($element, &$form_state, $complete_form) {

  global $user;

  $element['#tree'] = TRUE;

  // Normal FAPI field definitions, except that #value is defined.
  $element['user_email'] = array(
      '#type' => 'textfield',
      '#title' => t('Enter email address to add new administrator user'),
      '#size' => 45,
      '#maxlength' => 100,
      '#prefix' => '<span id="user_email">',
      '#suffix' => '</span>',
      '#element_validate' => array('my_module_user_management_validate'),
  );
  $element['add_button'] = array(
      '#type' => 'submit',
      '#value' => t('Add User'),
      '#submit' => array('my_module_user_management_submit'),
      '#validate' => array(),
      '#limit_validation_errors' => array($element['#parents']),
  );
  $element['administrators'] = array(
      '#type' => 'select',
      '#title' => t('Account Administrators'),
      '#default_value()' => array(),
      '#options' => field_view_field('node', $complete_form['#node'], 'my_module_administrators'),
      '#multiple' => TRUE,
  );

  return $element;
}

/**
 * An #element_validate callback for the user_management element.
 */
function my_module_user_management_validate(&$element, &$form_state) {

  if (!array_key_exists('user_management', $input = $form_state['input'])
      || !array_key_exists('user_email', $user_management = $input['user_management'])
      || !($email_address = $user_management['user_email'])) {

    form_set_error('user_management][user_email',
        t("An email address must be entered before pressing 'Add User'."));

  } else { // if $form_state['input']['user_management']['user_email'] has a value

    if ($email_address && !filter_var($email_address, FILTER_VALIDATE_EMAIL)) {
      form_set_error('user_management][user_email',
          t("User email must be a valid email address."));
    }
  }
}

/**
 * Form submission handler for add / remove buttons of user_management elements.
 */
function my_module_user_management_submit($form, &$form_state) {

  $email_address = $form_state['input']['user_management']['user_email'];

  $administrators_options[strval(count($administrators_options))] = $email_address;

  $form_state['rebuild'] = TRUE;
}

/**
 * Implements hook_node_submit().
 */
function my_module_node_submit($nodes, $form, &$form_state) {
  $administrators_options = $form['administrators_management']['user_management']['administrators']['#options'];

  foreach ($administrators_options as $email_address) {

    $new_user = user_load_by_mail($email_address);

    if (!$new_user) {
      $new_user = new stdClass();

      list($name) = explode('@', $email_address);
      for ($temp = $name, $count = 1; user_load_by_name($temp); $temp = $name . ++$count);
      $new_user->name = $temp;

      $new_user->mail = $email_address;
      $new_user->init = $email_address;
      $new_user->status = TRUE;
      $new_user->roles = array(
          DRUPAL_AUTHENTICATED_RID => TRUE,
          db_query("SELECT rid FROM {role} WHERE name = 'customer'")->fetchField() => TRUE,
          db_query("SELECT rid FROM {role} WHERE name = 'customer admin'")->fetchField() => TRUE,
      );
      $new_user = user_save($new_user);
    }
  }
}

```

# Answer
The file module uses AJAX which is why the validation errors appear in its container element (it's probably the reason for the other thing you mentioned as well). There is no `#ajax` on any of your elements so that would probably account for the behaviour you're getting, which would be that of a standard form.

It says right in the docs for it:

> This rebuilds the form element for a particular field item. As long as the form processing is properly encapsulated in the widget element the form should rebuild correctly using FAPI without the need for additional callbacks or processing.

See also how `inline_entity_form` implements the `inline_entity_form_single` widget, which is what you're basically reimplementing here.
> 1 votes

---
Tags: 7, forms
---


# Question
Title: How do I create custom 403/404/406/503 pages in Drupal 8?
I am familiar with creating node and pointing to that specific node in basic site settings. How do i create this programmatically and package in features? Twig override?

# Answer
To bundle and create programatically, you would need to create a custom module and inside that module: you could create a route for each specific page. That module could also update the config that is found in the system basic settings to use your custom pages.

Using this custom page you could call a custom page.html.twig and override with the html you need.

Here are two resources:
> 1 votes

# Answer
With regard to the 400 class errors it looks like this is possible (but not yet easy) with Drupal 8 - see https://www.drupal.org/node/2363987

It will need someone to write a contrib module to make this a simpler process at this stage.

A 503 error may not allow Drupal to return a complete page, or any page at all, so one might normally rely on a web server, cache server or CDN to serve a page result up for this kind of response.
> 0 votes

---
Tags: theming
---


title: theme preprocess view

text:
# Question
Title: theme preprocess view
I have a content type "Slide" that I use for a carousel in a view as a block. One of the field of the slide I have added is "country filter" that I intent to use as a filter for geo localisation. I use GeoIP2 for this.

My intent was to use a `THEME_preprocess_SOMETHING()` to alter the view and remove some of the slides that are not on the right country filter. For example some slides could be allowed to be shown only to user located in France. If the user is not located in France, I would remove those slides.

I tried to do this in a `THEME_preprocess_view_view_fields()` but I can seem to find a way to remove completely the slide. So I guessed I was not on the right hook.

Does anyone knows which hook I should use to do that?

# Answer
I haven't found a way to do it in a THEME.theme file but I found a way to do it in a MODULE.MODULE file. The magic hook is MODULE\_views\_post\_execute:

```
function feature_carrousel_views_post_execute(\Drupal\views\ViewExecutable $viewExecutable){
  /** @var \Drupal\views\Entity\View $view */
  $view = $viewExecutable->storage;
  if($view->id() == 'carrousel'){
    /** @var \Drupal\views\ResultRow $row */
    foreach($viewExecutable->result as $key => $row){
      $nid = $row->nid;
      /** @var \Drupal\node\NodeInterface $node */
      $node = \Drupal\node\Entity\Node::load($nid);
      if($node) {
        $country_filter = $node->get("field_country_filter")->getValue();
        $country_filter_tid = (reset($country_filter))['target_id'];
        /** @var \Drupal\taxonomy\Entity\Term $term */
        $term = \Drupal\taxonomy\Entity\Term::load($country_filter_tid);
        $name = $term->getName();
        $countryCode = getUserCountry();

        if(strtolower($name) != 'all' && strtolower($name) != strtolower($countryCode)) {
          unset($viewExecutable->result[$key]);
          $viewExecutable->result = array_values($viewExecutable->result);
        }

      }
    }
  }
}

```

Cheers
> 1 votes

---
Tags: views, 8, hooks
---


# Question
Title: Recipes for most compatible slideshows and/or carousels?
I'm getting ready to implement a carousel for client in Drupal 7. I've been searching for information about how to implement carousels and slideshows for maximum compatibility. I've installed several modules in my search and I realize that there is not an out of the box complete solution.

Most of the modules I've tried will make a mess of the page when js is disabled, some of them are buggy on mobile devices etc. I've seen some CSS3 solutions but haven't tried them yet by reason of not knowing the classes employed by them and the level of support they have in browsers/devices. I'd like to ask the community for what solutions exist aside from not using carousels and slideshows to accomplish this. A reasonably compatible solution that looks and functions ok, even on non js enabled browsers.

# Answer
> 2 votes
The most common formula I implement can work for just about any JS library.

Assuming you are attaching slides to a content type, here is how I go about it.

First, you will need File Entity, for the ability to add fields to file types.

You can use the default Image type, or, create a special one like 'Slide', if you'd like to isolate field and behavior.

1. Add an image field to a content type. Set the widget to 'Media' embed.
2. Set cardinality
3. Hide field display from all view modes
4. Create a new view mode, called 'Slideshow' or 'Carousel' whatever you desire
5. In the new view mode, set the image reference field to render the image in a view mode from the file entity configuration.
6. In Image (or your new) file type, add some fields like Title, Text, and Link. Configure the chosen file display to set those fields however you like.
7. Create a template representing that file display with the markup you desire and placement of fields.
8. Create a View, add a Block display, and add a contextual filter of node nid, based on url value (when on node pages).
9. Set the view to only output the Rendered Entity: Slideshow mode. No fields.
10. Put the block in your designated slideshow region.

When adding images on the content type(s), you should have a ctools window after uploading that presents the fields you added in step 6 - that is for setting headers, text, and 'read more' link on each image.

This will output the markup you provided in those templates on nodes who have one or more files attached. From here, you would want to tweak markup to match whatever slide JS library you select and some CSS tweaking as well. Then, you can hook up an initializer in a JS file in your theme, to call as you need.

This might take 30-60 minutes to setup, but it has been the most bulletproof way for me to allow someone to add a slideshow or hero (just 1 image) to a content page while being open and flexible to whatever slide/carousel library may be required.

My favorite plugins/libraries for slide functionality are Zurb Orbit and slick.js. I don't usually need or implement any modules to do these anymore, for the smallest possible implementation without a ton of overhead.

That said, if you are perhaps using a Foundation based theme, you might find it worthwhile to leverage Field Orbit. It is built a little like the steps above, but uses a field formatter to simplify the implementation part. Disclaimer, I built that many moons ago - but I have not made any changes to it lately. I believe it works with Foundation 5.x as well.

---
Tags: 7, theming, javascript
---


# Question
Title: Drupal Commerce product display text input on specific option
I have a Product Display that shows a group of products with color and size options. However, I want to show "Custom" as a color option, and if the user selects it, I want a text box to appear where they can input custom text. I can do a custom submit hook to handle the input no problem, but is there a "Drupal way" to add a text box on a certain product option?

# Answer
> 2 votes
you can use drupal conditional field module , and then on a certain value configure your text field to be displayed . conditional fields

---
Tags: 7, commerce
---


title: Webform Worflow notifaction

text:
# Question
Title: Webform Worflow notifaction
I'm using D7, WebForm Module and Workflow Module.

When the user submit, the state change automatically to the first state.

Users to notify and the submitter user should receive normally the notification.

When i try nothing received!

Can anyone suggest to me, What can i do to prevent this problem from happening?

# Answer
> 1 votes
Without more information on the issue, there could be a lot of causes for this. For example, most emails are sent when cron runs, is cron set to run periodically?

Are you able to see your logs on the site?

If so, are there errors associated with email not being sent (Go to http://your-site-url/#overlay=admin/reports and select recent log messages)? Is your server configured to sent emails?

Some error logs are found on your **/etc/httpd/logs/error\_log** folder, looking there would be helpful too while you try and submit a form to see what gets logged.

As I mention above, more info perhaps can help us troubleshoot it.

Hope this helps.

---
Tags: 7, webforms, workflows
---


# Question
Title: Create defaults for panels to be deployed on install only
We have a mini panel that we use to create a footer area. This is deployed on install of a new multi-site through our custom installation profile. I would like to set default content items in the panel regions on install. If I were to do this in a feature, then any changes made by the site administrator would be reverted on a features-revert-all command. How do I go about creating this as part of an install file?

# Answer
To start, I created my mini panel as I wanted it to be and did an export. I saved the export code to a file in a custom module I created. I used install file in the module and this hook\_install function:

```
function custom_footer_install() {
  if (!ctools_export_crud_load('panels_mini', 'fat_footer')) {
    $filename = drupal_get_path('module', 'custom_footer') . '/panel_exports/profile.txt';
    $handle = fopen($filename, "r");
    $contents = fread($handle, filesize($filename));
    fclose($handle);
    $panel = ctools_export_crud_import('panels_mini', $contents);
    ctools_export_crud_save('panels_mini', $panel);
  }
}

```
> 0 votes

---
Tags: 7, panels, installation-profiles
---


# Question
Title: Create multiple users roles and views at the same time
I'm using D7, I need to create views and user roles, when I'm using the interface mode, it takes me too much time, how can I do that using code? or could you please suggest to me a module to install, that can create, for example 10 roles at the same time, or cloning a view 5 times at the same time.

# Answer
The best way to programmatically create roles (and ideally set permissions for those roles), as well as create a view via code would be to use the features module. Views can be exported to an array of settings which can then be added with a feature.
> 0 votes

# Answer
If you set up Drush, which is is a command line shell and Unix scripting interface for Drupal, then you can create a role with the command:

drush role-create

This command accepts and requires 2 arguments, the first one defines the machine name of the role and the second one the human readable name. For example:

drush role-create 'my\_new\_role' 'My New Role'

Would create the role 'My New Role' with a machine name 'my\_new\_role'

Drush can also be used to quickly create views. Due to the variety of possible setups depending on your use case, it is probably best to start by looking at the documentation on https://drushcommands.com
> 1 votes

---
Tags: 7
---


# Question
Title: Can I have separate playlist for each node?
I have this problem: I have a nodetype Audiobook. In this page I set title, ahthor, description and other informations. I want to insert episodes of this audiobook in a playlist that user can display on audiobook page. When user clicks on an episode, it plays automatically. I'm trying to use mediafront, but I must create a view for each list, it's tedious. I tried to use nodehierarchy, by creating a content tuype "episode", but, when I click on one it opens a page and I can't switch to next easily. Any idea? I searched the internet, but there's doesn't seem to be no module.

# Answer
It sounds like you want a second content type called episodes. You can do this by adding a relationship between the audiobook and episodes with an entity reference field. When creating the field you can define how the relationship works. Episodes can then be ordered and you can setup a single view to display the episodes for a particular audiobook in which ever way you choose. The view would accept the audiobook node id as an argument selecting episodes by relationship for extra ease of development and simplicity.

You could also use the inline entity form module to add and edit related entities.
> 1 votes

---
Tags: 7
---


# Question
Title: Convert vertical (portrait) picture to horizontal (landscape), filling empty space around with blurred background
How can I do this in Drupal 7?

**Note:** Original question was here.

# Answer
I have created custom module called "Blurred". It can be described as "*post scale blurred background effect for images*".
> 1 votes

---
Tags: 7, media
---


title: How to delete pages created in panels?

text:
# Question
Title: How to delete pages created in panels?
I have some testing content that I played with in panels, but there is only disable options. They are on accessible on this URL:

```
admin/structure/pages

```

How to delete these?

# Answer
> 1 votes
First, check your user's role has the permission to delete panel pages and or nodes.

When there is no delete button under the clicked triangle, and these are Panel nodes, they might be deleted from the node manager and not from Panels (I used it a long time ago for 2-3 panel-nodes and I don't recall exactly if it's there).

---
Tags: nodes
---


# Question
Title: hook_form_alter and fields in user_profile
I know how to use hook\_form\_alter, but I'm little confused how to achieve this:

In user profile there are tabs "View" and "Edit".

In edit I can alter the form using switch statement on user\_profile\_form and adding a fields, but they don't appear when I click on "View" tab.

Let's say I'm adding a new field into the user\_profile\_form:

```
    <?php

    /*
     * Implements hook_form_alter().
     */

    function my_module_form_alter (&$form, &$form_state, $form_id) {
            switch ($form_id) {
            case 'user_profile_form':

    $form['account']['skype_title'] = array(
            '#type' => 'markup',
            '#markup' => '<div class="user-profile-skype">Skype edit</div>'
            );

            $form['account']['skype'] = array(
            '#type' => 'textfield',
            '#title' => t('New Skype'),
            );

                  //krumo($form);
            break;

    }
}

```

How can I display this field into "View tab"?

Should I use another hook for this?

# Answer
As Kaido24 mentioned, the profile view tab is not a form. You can add elements to it in hook\_user\_view\_alter().
> 1 votes

# Answer
View tab is rendered view not a form. If you would like to show something at view tab then iguess you could use the hook\_page\_alter.
> 0 votes

---
Tags: hooks
---


# Question
Title: How do I append a country to a views exposed filter field geofield proximity?
Using Geofield with Google's API, when a user enters "Vancouver", it assumes I mean "Vancouver, Washington", when I actually want "Vancouver, BC". Is there any way to append "Canada" to the location info submitted to google?

It would be nice if I could do this with some override but will accept a hack to the module and I will just keep track of the modified module.

Here is a link to Geofeild's code that covers this. http://pastebin.com/Diwj5deE

Note: That I just need the country appended to the info sent to google. I don't want the filter to have a default of "Canada" and it can't prefilter the view with "Canada". It is not until the user actually uses the exposed filter.

# Answer
> 2 votes
As with any form, a custom module can modify the `#submit` array to put a submission handler in front of the views exposed filter form to preprocess the data.

Here we're just modifying the submitted origin value so that " Canada" is appended if any text is entered by the user:

```
/**
 * Implements hook_form_views_exposed_form_alter().
 */
function MYMODULE_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
  array_unshift($form['#submit'], 'MYMODULE_form_views_exposed_form_submit');
}

/**
 * Modify submission value if given origin has been supplied.
 */
function MYMODULE_form_views_exposed_form_submit($form, &$form_state) {
  if (isset($form_state['values']['field_geofield_distance']['origin']) &&
      strlen($form_state['values']['field_geofield_distance']['origin']) > 0) {
    $form_state['values']['field_geofield_distance']['origin'] .= ' Canada';
  }
}

```

---
Tags: views
---


# Question
Title: Remove tasks and index when creating a menu tab from views
I am using views to create a menu tab for my views page and it works fine accept it comes with two unexpected tabs: Tasks and Index, which are showed in the photo below. Is there any way to remove them? Thanks.

# Answer
You can achieve this using hook\_menu\_local\_tasks\_alter hook.

> Alter tabs and actions displayed on the page before they are rendered.

```
function hide_tabs_menu_local_tasks_alter(&$data) {
    foreach ($data['tabs'][0]['output'] as $key => $value) {
        if ($value['#link']['path'] == "check your path") {
          unset($data['tabs'][0]['output'][$key]);
        }
    }
}

```

You can also take a look on Tab Tamer module.

> Tab Tamer is an administration utility that provides easy re-ordering, hiding, and deactivation of tabs and subtabs. You can also rename tab labels.
>
> Tab Tamer makes use of Drupal's drag ordering, but degrades gracefully when javascript is disabled.
>
> Tab Tamer utilizes Drupal's cache system to help conserve server resources.
> 1 votes

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


title: Add fields to user from a custom module

text:
# Question
Title: Add fields to user from a custom module
I'm building a small custom module and I should somehow extend default user entity by adding about 20 more fields to it.

I located User class definitions from Drupal folder (\drupal-8.1.8\core\modules\user\src\Entity\User.php). There I can see field definitions but that's not right place to do modification for sure :)

Also, I suppose I should add User module as a dependency to my custom module, even though user module is part of the core?

I've done some research and I think I should implement a plugin, but I don't know how exactly and what plugin interface to implement etc.

# Answer
> 7 votes
**Base fields**

You can add base fields to the user entity in a hook:

```
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Field\BaseFieldDefinition;
/**
 * Implements hook_entity_base_field_info().
 */
function mymodule_entity_base_field_info(EntityTypeInterface $entity_type) {
  if ($entity_type->id() === 'user') {
    $fields['field1'] = BaseFieldDefinition::create('text')
      ->setLabel(t('New field 1'))
      ->setTranslatable(TRUE);
    return $fields;
  }
}

```

**Bundle fields**

But most times you probably want to use bundle fields, which can be added and modified in UI and can be easily deployed through configuration. In D8 the user entity is fieldable like nodes.

See this tutorial:

Programming custom fields into your content type

You can apply the same procedure to users. Replace `node` with `user`, also the content type with `user`, because the user entity has no bundles and then you use the entity name as replacement.

In a standard install `user_picture` is the only user field configured out-of-the-box, which you can use as an example:

```
/core/profiles/standard/config/install/field.field.user.user.user_picture.yml

```

You can see that `user` is twice in the config name, for the entity type and the bundle name.

**How to add the fields**

The easiest way to implement this in a custom module is to add the fields in UI

```
/admin/config/people/accounts/fields

```

and then export the configured fields:

```
/admin/config/development/configuration

```

If you export the complete configuration before and after you've added the fields you can make a diff to catch all new yaml files.

Put the new configuration files in `/config/install` of your module like in the example above where it is in the same folder of the core standard profile. If you put exported config files in the module install folder remove the uuid: and \_core:default\_config\_hash: lines.

---
Tags: 8, users
---


title: Create Table With Aggregated Dates

text:
# Question
Title: Create Table With Aggregated Dates
I'm trying to create a table which aggregates all full date (Year-Month-Day) values into the Year. The issue I'm facing is that, even though I managed to achieve that, view still somehow sees day and month of the date field, and shows them as 2 different records.

In the end I'd like to plot that data into the charts module and receive a result of Number of Items vs their Age

These are the screenshots of my view as I have it right now.

# Answer
> 0 votes
You can use different formatters for the exact same field when you are in a different context. So, while the full node is shown, you can use the full date (as set in CT's Manage Display). When displaying the date in views, you can use the time ago. For correct grouping, add the date field once more, exclude it from display, then set the formatter to a custom one which only shows the year and finally use that rendered output to group the view's rows.

# Answer
> 0 votes
I've run into issues like this in the past. I'm not 100% sure this is correct but you may try this and see if it works for you.

One of the issues of aggregating by dates is that the Views aggregation happens during the database query stage, but the display of "Time ago" happens later, during the rendering stage. Therefore, when the date is converted to "years ago" it's already too late for aggregation.

I've found that Views Date Format SQL has helped me solve this issue in the past. This module...

> The Views Date Format SQL module allows to format date fields using SQL. This enables group aggregation for date fields using the choosen granularity.
>
> The core functionality is to remove the date formatting from render() and put it in query(). I.e. format date values using SQL's DATE\_FORMAT rather than PHP's format\_date. This is achieved by assigning a new default handler to node 'created' and 'changed' date fields. This handler extends and overrides views's build in views\_handler\_field\_date.

Another one to try if that doesn't work is to avoid using Views `aggregate` option altogether and use a post-query aggregation like Views Aggregator Plus.

---
Tags: views
---


title: How do I call legacy PHP files?

text:
# Question
Title: How do I call legacy PHP files?
I am unable to call PHP files inside the Drupal directory. My task is maintaining staff's old pages on the new platform. With pages written on clear HTML, there is no problem: I place files in a folder I created (domain.org/sites/default/files/share/staff\_folder).

In sites/default/files/.htaccess I added `DirectoryIndex share` and now the link to the domain.org/sites/default/files/share/staff\_folder/index.html can be used. When I import pages written in PHP, e.g. calling domain.org/sites/default/files/share/staff2\_folder/index.php, I get a 403 error:

> ### Forbidden
>
> You don't have permission to access /sites/default/files/share/staff2\_folder/index.php on this server.

While /sites/default/files/share/staff2\_folder/index.html still works.

# Answer
This is the part of `.htaccess`, which controls the access to php files:

```
  # For security reasons, deny access to other PHP files on public sites.
  # Note: The following URI conditions are not anchored at the start (^),
  # because Drupal may be located in a subdirectory. To further improve
  # security, you can replace '!/' with '!^/'.
  # Allow access to PHP files in /core (like authorize.php or install.php):
  RewriteCond %{REQUEST_URI} !/core/[^/]*\.php$
  # Allow access to test-specific PHP files:
  RewriteCond %{REQUEST_URI} !/core/modules/system/tests/https?.php
  # Allow access to Statistics module's custom front controller.
  # Copy and adapt this rule to directly execute PHP files in contributed or
  # custom modules or to run another PHP application in the same directory.
  RewriteCond %{REQUEST_URI} !/core/modules/statistics/statistics.php$
  # Deny access to any other PHP files that do not match the rules above.
  # Specifically, disallow autoload.php from being served directly.
  RewriteRule "^(.+/.*|autoload)\.php($|/)" - [F]

```

You can see, how the access for `statistics.php` is allowed. You can add your own rules (at your own risk).
> 4 votes

# Answer
Just create the pages by going to Admin \> Content \> Add Content \> Basic Page (or content type that is most applicable). There is no need to serve static PHP files within Drupal. Drupal is a content management system.

Knowing nothing about your content structure, it is up to you to attach fields to a content type for these pages that would best represent the data within them - use Drupal for its strengths, this is one of them. Revert all the changes to the .htaccess and apache conf files, it is not necessary.

For security reasons, you definitely do not want to have .php files in sites/default/files, a directory which may inadvertently be set to 777 permissions and open up multiple holes.

edit: I thought you said they were 'staff' web pages, but now I see that you might mean different sites the staff maintained. In which case you would want to look into multisite with Drupal, but with the same content management methodology applied.
> 0 votes

---
Tags: 8
---


# Question
Title: Drupal How to add javascript to ctools modal popup
I need to hide some element with some condition using jquery inside ctools modal popup in drupal after popup load. I used `drupal_add_js` but that not work.

Any suggestion?

# Answer
You must use: `ctools_ajax_command_attr('selector','attr','value');` do perform any kind of actions in popup. For more you can read: http://drupalcontrib.org/api/drupal/contributions!ctools!includes!ajax.inc/7
> 2 votes

# Answer
into custom modal style where you outputing your page callback add ctools\_add\_js('your\_js\_file\_without\_extension', 'MODULE\_NAME');

then in js

```
jQuery(document).ready(function($) {
Drupal.behaviors.MODULE_NAME = {
  attach: function (context, settings) {

     //your jquery code...

  }
}; });

```

For example you can copy ctools-ajax-samples.js from ctools directory and modify it as i did. This solution worked for me
> 0 votes

---
Tags: chaos-tool-suite, javascript
---


# Question
Title: How can I prevent height/width attributes on images run through the theme system?
My site runs now on Drupal 7.9. On the release notes (4th position) it is reported the following note:

> Restored height/width attributes on images run through the theme system

That is exactly what I don't want, because my images get distorted.

How can I prevent height/width attributes on images run through the theme system?

# Answer
> 3 votes
I resolved this by adding the dimensions with CSS.

# Answer
> 3 votes
**History**
In Drupal 6, populating width/height attributes caused a filesystem lookup (bad for back-end performance) for every image. This was fixed in #908282: Remove unnecessary I/O from theme\_image() by removing the height/width attributes altogether in Drupal 7.

Images without height/width attributes are bad for front-end performance so work was done in Populate HTML image tags with dimension attributes (like D6 imagefield) without re-introducing I/O to add them back.

**Answer**
So you really want your images to have width/height but obviously not if they get distorted. The update functions for 7.9 were supposed to fix this, did you run update.php after upgrading to 7.9?

If you ran update.php then this might be a bug.

# Answer
> 2 votes
You can also try removing all the attributes with:

```
function hook_preprocess_image(&$variables) {
  foreach (array('width', 'height') as $key) {
    unset($variables[$key]);
  }
}

```

# Answer
> 0 votes
The best way to do it (just like in Drupal 7) is to use `hook_preprocess_HOOK()`.

In your `THEME.theme` file (where `THEME` is the name of your theme), define a function as such:

```
function THEME_preprocess_image(&$variables) {
  unset($variables['attributes']['width']);
  unset($variables['attributes']['height']);
}

```

Hope it helps. Happy coding!

---
Tags: theming, media
---


title: Send email when order status is changed

text:
# Question
Title: Send email when order status is changed
I need to send a message to the customer when I change the order status (e.g from pending to processing-completed-canceled). How can I do this with Rules?

# Answer
Rules is definitely the way to do this.

1. Create a new rule...

Name: Order Status Update Tags: React on event: **Commerce order \> After updating an existing commerce order**

2. Then, add an action. **System \> Send mail**
3. Email "To" value. Use the **\[commerce-order:mail\]** token
4. Fill out subject and message. Then save.

Updated: To make sure you dont send an email everytime the order is updated, set the following rules...

1. Add condition: Data Comparison. Commerce-order:status = Completed
2. Add "AND".
3. Add condition: Data Comparison. **Commerce-order-unchanged:status = Completed**, but check NEGATE.

This avoids having to enable the PHP filter module.
> 3 votes

# Answer
Set up the rule to use "Event After updating an existing commerce order". Add the condition "Execute custom PHP code". Then add the following code.

```
if("[commerce-order:status]" == "completed" && "[commerce-order-unchanged:status]" != "[commerce-order:status]") { return TRUE; } else { return FALSE; }

```

Then you can set up your email action.
> 0 votes

# Answer
It took me entirely too long to figure out how to do this with rules only, but here's what I have working:

```
OR
    AND
        Data comparison
        Parameter: Data to compare: [commerce-order:status], Data value (equals): Canceled

        NOT Data comparison
        Parameter: Data to compare: [commerce-order-unchanged:status], Data value (equals): Canceled

    AND
        Data comparison
        Parameter: Data to compare: [commerce-order:status], Data value (equals): Processing

        NOT Data comparison
        Parameter: Data to compare: [commerce-order-unchanged:status], Data value (equals): Processing

```

If you need additional status updates, you'll have to create and wrap each one so rules knows what to check through. I left out "Completed" because I want a completely custom message sent on completed orders.

Shoutout to @Colton Echols for making me mentally think it through with the php snippet.
> 0 votes

---
Tags: rules, emails, commerce
---


# Question
Title: How can I get a display name from the view ID and display ID?
I can load a view with `$view = Views::getView('my_view_id');`, but how do I use that object to load the display\_title or say an array containing information including the display name?

Note: This is not to be confused with loading the display's title that might be used when printing the view, as there's a method for that (`getTitle()`).

# Answer
> 19 votes
After reading throug the docs (https://api.drupal.org/api/drupal/core!modules!views!src!ViewExecutable.php/class/ViewExecutable/8), I tried the following (which worked):

```
$view = \Drupal\views\Views::getView('your_view_id');
$view->setDisplay('your_display_id');
$displayObj = $view->getDisplay();
//$displayPluginTitle = $displayObj->pluginTitle()->render();
//$displayTitle = $displayObj->getOption('title');
$displayName = $displayObj->display['display_title'];

```

N.B.1: I use the render function on a TranslatableMarkup object, this is what the pluginTitle function returns. It could be possible to use other functions there, like, e.g. getUntranslatedString
N.B.2: I misunderstood the OP. :-) Commented out the faulty part of the code, which returns the display plugin's title, and not the display's title as requested.
N.B.3: I misunderstood the OP. AGAIN! :-) Commented out the faulty part of the code, which returns the title of the display, and not the display's name as requested. To my defense, that property is labeled 'Display name' and its name 'display\_title' (as was mentioned in the OP).

Screenshot from Views example:

And a test script that gets the title of the display (with the output):

Cheers!

# Answer
> 0 votes
The following code depends on the ctools\_views module.

```
$view = \Drupal\views\Views::getView('your_view_id');
$view->setDisplay('your_display_id');
$displayObj = $view->getDisplay();
$displayName = $displayObj->display['display_title'];

```

To get the display title only requires the following code.

```
$view = \Drupal\views\Views::getView('your_view_id');
$view->setDisplay('your_display_id');
$displayName = $view->getTitle();

```

---
Tags: views, 8
---


title: Adding font-size and color buttons

text:
# Question
Title: Adding font-size and color buttons
I work with Drupal 8.1.3 and my WYSIWYG editor lacks font-size and color buttons.

Is there a way to unlock these or should I install a total different editor (while trying to convince some in the community to bring these options back)?

# Answer
You are looking for the ColorButton and CKEditor Font Size and Family plugins. Follow the instructions on the project pages and you'll have the option to add those back to the toolbar.

Beware that because these plugins use inline styles, the effects will be removed by Drupal's XSS filtering mechanisms if the format has "Limit allowed HTML tags and correct faulty HTML" enabled.

There is currently no way (that I know of) to have both filtered markup and inline styles. There is currently no equivalent of D7's WYSIWYG Filter module for D8. Such a module would have to both implement a new filter of type `Drupal\filter\Plugin\FilterInterface::TYPE_HTML_RESTRICTOR` and the hook `hook_editor_xss_filter_alter()` to override the use of `\Drupal\editor\EditorXssFilter\Standard` in the Editor module (that class extends `Drupal\Component\Utility\Xss` and calls its filter method, which in turn is hard-coded to always remove style attributes.

**Update**: The htmLawed module does provide an alternative to Core's filter, so you can configure it to not strip style attributes during rendering. Ensuring that configuration safe is another matter, but just adding the 'span' tag in the list of allowed tags and removing 'style' from the list of disallowed attributes got me *partially* there.

I say *partially* because as soon as you try to edit the saved content or switch to another format and back, the style attribute will still be stripped by Editor module. When you switch to a format with an editor enabled Editor module's script will make an AJAX call to the server and pass the contents of the original textarea to be filtered before sending it into the editor. (When an editor is attached on page load, this happens as part of generating the form so no AJAX call is needed until the format switch.)

It is during this process which the XSS filtering is still messing with the inline style attribute, as the call to `Xss:filter()` still blacklists it. The htmLawed module (or another module) would have to perform the aforementioned class replacement to get rid of this feature/problem completely.

So, as long as you re-apply inline styles each time you edit the content, and do not switch between editor formats while doing so, you *can* get font colors and sizes done, though it's currently a bit impractical and not very intuitive.
> 5 votes

# Answer
Open **Administration -\> Configuration -\> Content authoring -\> Text formats and editors** `admin/config/content/formats` and **Configure** the text format you are using. Then drag and drop the buttons you want to use in your editor in the **Toolbar Configuration** section and click **Save Configuration**.

To add custom styles to the editor like different font colors & font sizes, drag the **Styles**-button to the toolbar. You will get a new tab below called **Styles Dropdown**. In that tab you can add your own Style options. So if you want to add a possibility to add **Heading 2** content in your editor, add the line `h2|Heading 2`. If you want to add text that is red color, add the line `.color-red|Red color` and then in your CSS file define `.color-red { color: red; }` and so on.
> 0 votes

---
Tags: 8, wysiwyg
---


# Question
Title: Why did all my themes disappear when I upgraded to PHP 7?
Today I had to do some support on a Drupal 6 website and when I tried to refresh a CSS file, all the themes disappeared. When going to the theme page, nothing in the list at all. Not even the core themes.

This is a Drupal 6.x website and I am running it on my current development system which runs PHP 7.x among other things.

Why would my theme disappear like that?

Note: I tried clearly all the cache tables and click on the "Clear all Caches" and the caching is turned off in the Performance screen (so that way I know it's not that creating problems.)

# Answer
> 3 votes
I don't know specifically why your themes disappeared, but the requirements page for Drupal (https://www.drupal.org/docs/7/system-requirements/overview) states:

> Drupal 6: PHP 5.x only (5.2.5 or higher recommended). Warning: support for PHP 4.x has been dropped. Drupal core should work with PHP 5.3.x, but PHP 5.3.x and higher may produce errors or unexpected behavior especially for contributed modules and themes.

PHP 7 is definitely not supported. You will likely find many more errors than this over time.

# Answer
> 0 votes
After a couple of hours looking at the code, I finally found the problem:

There is a function in `file.inc` that uses `preg_match()` with a pattern where no delimiters are added. Whoever was maintaining that line of code, just put a '@' in front of it, instead of properly adding the delimiters.

There is the offensive line (around 1095):

```
elseif ($depth >= $min_depth && @ereg($mask, $file)) {

```

**Note:** The correct line says `@ereg()` which does not require the delimiters, so when I changed that to `preg_match()` so it works with PHP 7, the delimiters became required.

*(Notice the `@` character in there? Even with PHP 5 you'd get some kind of error message on that line without it!)*

The `$mask` variable is a regular expression, but all are missing the delimiters (for example: `"\.info$"` to search for the *theme.info* files.)

There is my proposed fix. I just add "/" before and after the mask, and just in case, escape any slash that would be appearing inside the name.

```
elseif ($depth >= $min_depth && preg_match('/' . str_replace('/', '\\/', $mask) . '/', $file)) {

```

---
Tags: 6
---


# Question
Title: Relation vs. References vs. Entity Reference for managing node-reference-type relationships
It seems like there are several active modules that all have similar functionality. Can anyone offer any information as to which branch appears to be the most promising / likely to survive & thrive? Any advice is welcome.

# Answer
> 6 votes
I've tried them all for an upcoming project. And the way i see it, only use Relation if you're dealing with complex relationships, not one-to-one references. If what you need is a basic reference, I'd go for references or entityreference.

I think that the last update concerning a widget for Relation, is that they're going to drop the idea, and consider Relation as an API only module. But who knows?

One note, if you want to use entityreference and field\_collection together - it's buggy. Just fyi.

# Answer
> 13 votes
As of March 2012, the References module project page is now recommending Entity Reference as a replacement.

For basic node-type references, Entity Reference is certainly easier to set up than Relation. I think a good general rule would be

> If you can do what you want with Entity Reference, use that. Otherwise, go with Relation.

# Answer
> 2 votes
Relation is planned as a replacement for References. Visit the Drupal.org/modules/references or /relation pages. Relation looks very good, but is not fully implemented yet. They have been working on widgets to create the relationships, but have also had some problems. Despite the limitations current widget I like the relation module capabilities. I have been working using both as I get more familiar with Drupal.

# Answer
> 0 votes
I recommend using Entity Reference & Views instead of Relation if possible. For those wondering about the differences, I wrote a blog post on how to install Relation as well as its advantages and disadvantages. I hope this helps some people.

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


# Question
Title: Custom translatable content entity appears twice when choosing the entity type to create a view
I'm Developing a custom module with custom content entities that needs to be translatable. The problem is that when they are made translatable by adding: translatable = TRUE in the @ContentEntityType annotation, the entities appear twice in the drop down view setting options (check the image, 'Faculty' appears twice) which is really strange.

I don't mind if they show twice or more than that but the problem comes when you decide which to choose to create your view because one of the options results in only the entity label field(name) available for building the view, of course along with other unnecessary fields to my use caes such as UUID, created, changed, ..etc . However, the other option has the other fields that I added to the entity through the Manage fields UI and those are the ones I need.

I have done what this page at drupal.org stated { if the 'translatable' annotation has value TRUE} define a class that extends \Drupal\content\_translation\ContentTranslationHandler, to translate the content.

There is no handy resource to learn how to impelement the TranslationHandeler class. So I have followed the one used in core of 'Taxanomy' entity which basically looks like it would work with any other entity. You just need to rename it! - correct me if I'm worng! Also, by the way translation of the entity works fine even in instances where I didn't define the TranslationHandaler class and I just included 'translatable = TRUE' annotation, which also is strange!!

I have tried every thing I could to fix it and researched for hours but with no luck. The two options dissappears if you don't include translatable = TRUE in the annotation but then you can not translate the entity fields this way.

My drupal version is 8.1.0 and I have used drupal console on windows to generate the module and the entities. Then I added the extra code.

Anyone could help please!

Code for defining TranslationHandeler class

```
namespace Drupal\registerar_office;

use Drupal\Core\Entity\EntityInterface;
use Drupal\content_translation\ContentTranslationHandler;
use Drupal\Core\Form\FormStateInterface;

 /**
 * Defines the translation handler for faculty.
 */
class FacultyTranslationHandler extends ContentTranslationHandler {

 /**
  * {@inheritdoc}
  */
  public function entityFormAlter(array &$form, FormStateInterface $form_state, EntityInterface $entity) {
    parent::entityFormAlter($form, $form_state, $entity);
    $form['actions']['submit']['#submit'][] = array($this, 'entityFormSave');
  }

  /**
   * Form submission handler for TermTranslationHandler::entityFormAlter().
   *
   * This handles the save action.
   *
   * @see \Drupal\Core\Entity\EntityForm::build().
   */
  function entityFormSave(array $form, FormStateInterface $form_state) {
    if ($this->getSourceLangcode($form_state)) {
      $entity = $form_state->getFormObject()->getEntity();
      // We need a redirect here, otherwise we would get an access denied page,
      // since the current URL would be preserved and we would try to add a
      // translation for a language that already has a translation.
      $form_state->setRedirectUrl($entity->urlInfo('edit-form'));
    }
  }

}

```

# Answer
> 1 votes
I don't think it's directly associated with translation handling - it looks like it's the distinction between the entity and entity\_field\_data table. The "working" option in the dropdown is a class derived from WizardPluginBase.

I fixed my problem by making sure both of these were in my Drupal\custom\_entity\Entity\CustomEntityViewsData::getViewsData

```
$data['custom_entity']['table']['wizard_id'] = 'custom_entity';
$data['custom_entity_field_data']['table']['wizard_id'] = 'custom_entity';`

```

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


# Question
Title: What would be best method to append bootrap css to non bootstrap themes but not affect layout?
I want to use Adaptive themes, I like the layout options, however, I like the Bootstrap look and feel.

So I want Adaptive theme layout css with boostrap visual css basically.

What would be the best way to achieve this short of getting into the HTML of Adatptive them and changing all the classes on elements?

# Answer
> 1 votes
You can customize your bootstrap package for download here:

> Customize Bootstrap's components, Less variables, and jQuery plugins to get your very own version.

http://getbootstrap.com/customize/

After that, you can add just the required CSS/JS to your theme as per the usual methods

---
Tags: theming, bootstrap-theme
---


# Question
Title: trigger in rules a beep sound on user side (current user is working)
I have a D7 site running with Organic groups, rules, VBO, panels, badges, private-message modules ... and a bootstrap sub-theme (js, jQuery update, ...) working in all browsers, ios & android, i need to alert users with a beep sound when new OG content is created (or any rules reaction) by a custom module named beepsound module.

What I have:

• Rules event: create new content

• Rules condition: my contentype with some fields.

• Rules action: Loop: all OG group members, loop action: see code below

"beepsound module" must have UID variable to target a specific OG member.

I have manage to have my beepsound as an action in rules, it targets UID, it display a personalised message corectly, also, message is displayed 5 times (when tiggered when mycontentype is being viewed), meaning rule is triggered 5 times, here are my-module code files, dot module file exist but is empty (and not displayed here), If i run this rule with current-user, it works (makes a beep), but not in my OG loop, what it is wrong?

beepsound.info MODULE

```
name = Beep sound by rules module
description = Module to add a beep sound action in rules
package = Custom
version = 7.01
core = 7.x
dependencies[] = rules

```

beepsound.rules.inc MODULE

```
/**
* Implement hook_rules_action_info()
* Declare any meta data about actions for Rules
*/

function beepsound_rules_action_info() {
$actions = array(
'beepsound_action_beepsound_user' => array(
    'label' => t('Make a beep sound'),
    'group' => t('sound'),
    'parameter' => array(
        'account' => array(
            'type' => 'user',
            'label' => t('User to beep'),
            ),
    ),
  ),

);

  return $actions;
}

/**
 * The action function for produce sound
 */

function beepsound_action_beepsound_user($account) {
    drupal_set_message(t('Hello @username',
 array('@username' => $account->name)));
    ?><audio autoplay="autoplay">
      <source src="/sites/all/modules/beepsound/A-tone.ogg" type="audio/ogg">
      <source src="/sites/all/modules/beepsound/A-Tone.mp3" type="audio/mp3">
    </audio><?php
}

```

here is my rule

```
{ "og_og_new_content_notification_message" : {
"LABEL" : "OG new content notification message",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"TAGS" : [ "OG" ],
"REQUIRES" : [ "og", "rules", "privatemsg_rules", "beepsound" ],
"ON" : { "node_insert" : [] },
"IF" : [ { "og_entity_is_group_content" : { "entity" : [ "node" ] } } ],
"DO" : [
  { "og_get_members" : {
      "USING" : { "group_content" : [ "node" ] },
      "PROVIDE" : { "group_members" : { "group_members" : "List of group members" } }
    }
  },
  { "LOOP" : {
      "USING" : { "list" : [ "group-members" ] },
      "ITEM" : { "list_item" : "Current list item" },
      "DO" : [
        { "privatemsg_rules_new" : {
            "USING" : {
              "recipient" : [ "list-item" ],
              "author" : [ "node:author" ],
              "subject" : "\u0022[node:title]\u0022 a sido creado. ",
              "body" : "\u003Ca href=\u0022\/node\/[node:nid]\u0022\u003E Por favor haz clic aqu\u00ed para ver su contenido\u003C\/a\u003E"
            },
            "PROVIDE" : { "thread_id" : { "thread_id" : "ID of new thread" } }
          }
        },
        { "beepsound_action_beepsound_user" : { "account" : [ "list-item" ] } },
        { "drupal_message" : { "message" : "beep beep, usuario: \u0022[list-item:uid]\u0022" } }
      ]
    }
  },
  { "drupal_message" : { "message" : "Se ha enviado un mensaje a todos los miembros del departamento." } }
]

```

} }

# Answer
In order to send a message to users other than the current user, you will need to do some additional processing. `drupal_set_message` sets a message in the current user session. It does not set a message in another user's session.

Some possible approaches include a push or pull notification type system. For example, the server can push updates to the client using something interesting like a Service Worker (advanced). Alternatively, the client can poll the server periodically, via ajax type request to get message updates.
> 1 votes

---
Tags: 7, rules
---


# Question
Title: Quick edit destroys CKEditor formatting... any way to avoid it?
Quick edit doesn't bring up CKEditor buttons, and clears immediately all previous formatting (like numbered lists), which can lead to serious data lost, in my case. Is there any patch to have Quickedit SKIP those textareas at all, while allowing it to interfere in those more simple fields? Using 7.x-1.5 module version, Drupal 7.41 thanks

# Answer
> 1 votes
If you want to switch between text formats and not have your code erased go to:

/admin/config/content/ckeditor/edit/Advanced (for Filter HTML)

/admin/config/content/ckeditor/edit/Full (for Full HTML)

Then under Advanced Content Filter, select disabled.

---
Tags: wysiwyg, entities
---


# Question
Title: form Class, add a check function before the buildForm method
I generate a sample Class form (and routing) with the drupal console.

Then, I have my class with some defaults generated methods ; getFormId, buildForm...

When the user go to the url path defined in the routing file, the buildForm method is called for build the the form. I want call another function for check some datas before the buildForm method :

I function like :

```
function a_check_function_or_method_before_buildForm(...){
    // - Check some datas
    // - If all is ok, the buildForm can be called
    // - Else, if the custom function detect an error, the buildForm isn't called and the user is redirected to an error page
}

```

Is it possible to do that ? how can I do that ?

Thank you =)

# Answer
You can do all that inside of buildForm():

```
use Symfony\Component\HttpKernel\Exception\HttpException;

public function buildForm(array $form, FormStateInterface $form_state) {

  $data = a_check_function_or_method_before_buildForm();

  // throw an exception
  if (empty($data)) {
    throw new HttpException(500, 'No data connection.');
  }

  // or return an empty form with an error message
  if (empty($data)) {
    return $form['#markup'] = '<h1>No data could be collected!</h1>';
  }

  // build the form with $data

}

```

Another possibility would be to call first a controller, which then decides what to do, return a form or something else.
> 2 votes

---
Tags: forms, 8
---


# Question
Title: Using Exposed Form to filter by referenced entity
First, I'd like to start with my content structure:

```
Classrooms:
Title
Students_Attending [entity reference field with multiple values]

Students:
Name
Gender
Country
Classes
Avatar

```

Ok now, let's say I have a View that essentially lists Students. It has exposed fields for gender, country, and classes. You can use these to narrow down the subset of students listed by the view.

I want to add another exposed filter to this view. This filter will be a select box with a list of Classrooms, and you are able to select multiple classrooms. What this does in practice is that it limits the resulting subset list of Students to those that are referenced by the "Students\_Attending" entity reference field of the "Classroom(s)" that was/were selected. So if I select "Classroom 1" on the exposed filter, the View will only list students who are referenced by the "Students\_Attending" field of "Classroom 1."

How do I achieve this with Views on Drupal 8? Is it even possible with Views alone?

# Answer
It's not possible with views alone without custom code or another module.

See https://www.drupal.org/sandbox/el/2698765 or D8 entity reference exposed filter for ideas on how to proceed.
> 0 votes

---
Tags: views, 8, entities
---


# Question
Title: How do I integrate media (e.g. attaching audio) to nodes?
I installed the Media Entity module for Drupal 8. I thought it would somehow facilitate adding Mp3, etc, as Media does in Drupal 7, where I could specify a media player type for an audio file. (And things work fairly well.) I am updating my site to Drupal 8 and it seems the Media Entity module only acts as an API. Maybe I just need to wait for an official Drupal 8 release before I get too far in the weeds with media?

Since I am grabbing Mp3 files from my previous site, ideally there would be a media field to which I can, in code, just add the field info, with the rendering of the field being determined by the form display settings.

Anyway, I am sure a lot of people are trying to figure this out in Drupal 8, so if anyone has a good approach, I am all ears!

# Answer
To use mp3 files with Media entity you need the additional module "Media entity audio".

Alternatively, you can attach audio straight to nodes with the "Audiofield" module.
> 0 votes

---
Tags: 8, media, files
---


title: Provide default site uuid on install

text:
# Question
Title: Provide default site uuid on install
Can I provide default site's uuid static in Drupal 8. I am using docker with Drupal 8 and during configurations import the site is rebuild with docker resulting in different uuid each time. After that I am not able to import configurations.

Thanks

# Answer
> 0 votes
You can set the site uuid variable with drush, but a better solution is to use the "config\_installer" module.

See https://www.drupal.org/node/2583113 for related discussions.

---
Tags: 8, configuration
---


# Question
Title: Send argument to custom field constraint
I have created custom field type with custom constraint defined and called successfully, the question is how to send the field settings to my constraint in the code block below.

```
/**
 * Plugin implementation of the 'custom_field_type' field type.
 *
 * @FieldType(
 *   id = "custom_field_type",
 *   label = @Translation("custom field type"),
 *   description = @Translation("custom field type"),
 *   default_widget = "number",
 *   default_formatter = "number_integer"
 * )
 */
class CustomFieldType extends IntegerItem {
  /**
   * {@inheritdoc}
   */
  public static function defaultFieldSettings() {
    return array(
      'type' => array(
        '#type' => 'radios',
        '#title' => t('type Validator'),
        '#default_value' => 'none',
        '#options' => [],
        '#description' => t('types.'),
      ),
        ) + parent::defaultFieldSettings();
  }

  /**
   * {@inheritdoc}
   */
  public function fieldSettingsForm(array $form, FormStateInterface $form_state) {
    $type_options = array(
      'type1' => t('type1'),
      'type2' => t('type2'),
      'none' => t('type1 and type2'),
    );
    return array(
      'type' => array(
        '#type' => 'radios',
        '#title' => t('type Validator'),
        '#default_value' => $this->getSetting('type'),
        '#options' => $type_options,
        '#description' => t('types.'),
      ),
    );
  }

    /**
   * {@inheritdoc}
   */
  public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
    $properties['value'] = DataDefinition::create('integer')
      ->setLabel(t('type'))
      ->addConstraint('CustomCheck')
      ->setRequired(TRUE);
    return $properties;
  }
}

```

How to send the field settings as arguments to the constraint as the validation only takes the field value as parameter.

```
/**
 * Validates the CustomCheckConstraint.
 */
class CustomCheckConstraintValidator extends ConstraintValidator {

  /**
   * Validator 2.5 and upwards compatible execution context.
   *
   * @var \Symfony\Component\Validator\Context\ExecutionContextInterface
   */
  protected $context;
 public function validate($data, Constraint $constraint) {
//do custom check here
}
}

```

# Answer
The method addConstraint allows an optional array of options to be passed to the constraint plugin. See https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21TypedData%21DataDefinition.php/function/DataDefinition%3A%3AaddConstraint/8.2.x
> 0 votes

---
Tags: entities, 8
---


title: Redirect using a path

text:
# Question
Title: Redirect using a path
My question seems to be obvious but I really don't find the solution. Well, I want to redirect to my view just after connexion. I try to use $form\_state-\>setRedirect,but It's seems it needs the route name. I don't find the route name of my view! How to get a route name from a path? Or to redirect using the path?

# Answer
You can also use setRedirectUrl(), which needs a URL object. There are many ways to create one, for example for an arbitrary path: `Url::fromUri('base:some/path')`
> 8 votes

---
Tags: 8, routes, redirection
---


# Question
Title: In view, add a sample no global "link" field foreach row
I created a view from the user interface. This view shows some content of a type of node. For each node displayed, I want add a field "mylink custom" in this view for show a generated link.

I generate the link from a custom module, I want change the link according to the node displayed by the (row) view and some current user parameters.

How can I do that ?

I add a "Global : Custom text" default field in the user interface, but this field is global ! When I want get his value from a prerender hook view, I get only the global value for all nodes displayed in my view. But I want set a different value of my "custom link field" for each row of my view.

I didn't add a new field in my node structure because I want just display a generated text when the user go to the view page. I don't want save this value in each node because this text change each time an user go to the view page.

Thanks for help =)

# Answer
I find how do with this usefull guide

I created a custom field and I added it to my view. The content of my field is defined in the render method of the FieldPluginBase Class.

In addition, we can quicly and properly generate a FieldPluginBase Class and views.inc with drupal console (command 'drupal gpcf')
> 0 votes

---
Tags: views, 8, entities
---


# Question
Title: How to change slider widget price range text and "Go" label in KickStart Commerce?
How to change slider widget price range text and "Go" label in KickStart Commerce?

Want to remove "range from...." and change "Go" on the button to Russian "Найти".

What Drupal display view or template, page or module to change? Thank you (see fig. attached, please).

# Answer
Below is a work around. See if it works :

* Create a file custom\_string\_overrides.inc inside your custom module folder and add the below code:

```
$conf['locale_custom_strings_en'][''] = array(
  'Go' => 'Add replacement here',
  'range from' => 'Add replacement here',
);
```
* Add the below code to settings.php

```
include DRUPAL_ROOT . '/path-to-module/custom_string_overrides.inc';
```

The above trick does the string replacement and texts will be replaced where ever they appear. As I mentioned, this is just a workaround.
> 0 votes

---
Tags: commerce
---


# Question
Title: Display custom block to specific content type programmatically
I created one custom module, it will create one custom block when it is installed. I want to display it on "product" content type only. Can I do the same with programmatically. It'll save my time. Here is my code.

```
<?php
function my_module_block_info() {
    $blocks = array();

    $blocks['my_module_config'] = array(
            'info' => t('My Module'),
    );
    return $blocks;
}

/**
 * Implements hook_block_view().
 */
function my_module_block_view($delta = '') {
    $block = array();

    switch ($delta) {
        case 'my_module_config':
            $my_module_form = drupal_get_form('my_module_form');
            $my_module_form = drupal_render($my_module_form);
            $block['subject'] = '';
            $block['content'] = $my_module_form;
            break;
    }
    return $block;
}
?>

```

# Answer
This code should work for you

```
function my_module_block_info() {
  $blocks = array();
  $blocks['my_module_config'] = array(
    'info' => t('My Module'),
    'status' => TRUE,
    'region' => 'content',
  );
  return $blocks;
}

/**
 * Implements hook_block_view().
 */
 function my_module_block_view($delta = '') {
 $block = array();

 switch ($delta) {
   case 'my_module_config':
     $block['subject'] = '';
     $node = menu_get_object();
     if (isset($node->type) && $node->type == 'product') {
       $my_module_form = drupal_get_form('my_module_form');
       $my_module_form = drupal_render($my_module_form);
       $block['content'] = $my_module_form;
     }
     else {
       $block['content'] = '';
     }
     break;
  }
  return $block;
}

```
> 1 votes

# Answer
I got one solution but It's weird, It's working by this way.

```
function example_install() {
// Install our custom block visibility settings per node type
$query = db_insert('block_node_type')

->fields(array('type', 'module', 'delta'))
->values(array(
  'type' => 'my-node-type', // content-type
  'module' => 'example', // My module name
  'delta' => 'my-block-delta', // Same delta used in hook_block_info
))
->execute();
}

```
> 1 votes

# Answer
Clearly you know how to do it using admin UI in block configuration, If you don't want to use this option, Why don't you load the block in `Product` node pages instead of assigning it's visibility to this content type in the module?

---

Did you try hook\_block\_list\_alter ?

> This hook allows you to add, remove or modify blocks in the block list. The block list contains the block definitions, not the rendered blocks. The blocks are rendered after the modules have had a chance to manipulate the block list.

The Show block for specific content type programmatically can be helpful. The hook\_block\_list\_alter\_example.php is another example.
> 0 votes

# Answer
As I can see, the Drupal core save the block content types setting in function node\_form\_block\_admin\_configure\_submit(). I copied the code from node.module file. So I copied it and made my one here:

```
  // Say I have two blocks want to show on 'article' content type.
  $my_blocks = array(
    // Block 1: module is 'views' and delta is 'views-block-1'.
    array(
      'type' => 'article',
      'module' => 'views',
      'delta' => 'views-block-1',
    ),
    // Block 2: module is 'webform' and delta is 'client-block-1'.
    array(
      'type' => 'article',
      'module' => 'webform',
      'delta' => 'client-block-1',
    ),
  );

  // Insert settings into 'block_node_type' table.
  $query = db_insert('block_node_type')->fields(array('type', 'module', 'delta'));
  foreach ($blocks as $block) {
    $query->values(array(
      'type' => $block['type'],
      'module' => $block['module'],
      'delta' => $block['delta'],
    ));
  }
  $query->execute();

```

**Notice: Above code should only run once. I putted it into my module update script(my\_module.install). Otherwise you may need to add some checking to prevent duplicated records in 'block\_node\_type' table.**
> 0 votes

---
Tags: 7, nodes, blocks
---


# Question
Title: Errors when trying to install adaptive theme on D8 from backend GUI method
When I try to install the *Adaptive Theme* for Drupal 8 on https://simplytest.me/, I get the following error on /core/autorize.php.

> drupal 8.2.0-rc1
> Update manager
> Error message
> Installation failed! See the log below for more information.
>
> adaptivetheme
>
> Error installing/updating
> File Transfer failed, reason: Cannot copy /home/r1rkn/www/tmp/update-extraction-3b2e9e06/adaptivetheme/Gemfile.lock to /home/r1rkn/www/themes/adaptivetheme/Gemfile.lock.

This is for the latest Drupal 8 development snapshot version.

How can I fix this error?

# Answer
First thing is you don't install it.

All you have to do is make sure adaptivetheme is somewhere in the /themes/ directory.

Then download and install the AT Tools module and it's AT Theme Generator sub-module, then create a sub-theme via the UI (a tab in the Appearance section). The at\_core base theme will install automatically when you enable your sub-theme.

Also, this theme will never show up on the Appearance page, it's hidden deliberately, because it's just a collection of scripts and libraries that support features in sub-themes. It's never intended to be interacted with via a UI, or be set as default etc.
> 3 votes

---
Tags: 8, theming
---


# Question
Title: Drupal Webform is sending emails but there are no values
The email that my webform is sending only has this... no actual values as entered into the form?

Submitted values are: \[submission:values\]

Please help!

# Answer
> 1 votes
In the Webform configuration under advanced settings to configure the general Webform settings go to `admin/config/content/webform`

* Advanced settings : Check off `Allow tokens to be used in Webforms`

# Answer
> 0 votes
Try `%value[key]` once and check.

Example:

First Name: `%value[first_name]`

Last Name: `%value[last_name]`

---

OR

```
First Name: [submission:values:first_name]

```

---

---
Tags: 7, webforms, tokens
---


title: How can I call form function in html?

text:
# Question
Title: How can I call form function in html?
I have requirement in that I want to show a dropdown values. So to achieve this I created a form function with `select` type and returning the form. I want to display it in a html page. Here is what I have tried:

```
function cart_confirmation_form($form, &$formstate){

  $opt = array('Hi','Bye');
  $form['dropdown'] = array(
    '#title' => 'somethinfg',
    '#type' => 'select',
    '#options' => $opt,
  );
  return $form;
}
   function testing(){
     $message .= '<div class="popup-related-tabs" style="float: left;" >' . cart_confirmation_form($form, $formstate) . '</div>';
      $message .= '<div class="popup-related-titles" style="padding:15px;" id="popup-related-block">'.$form_message.'</div>';
    drupal_set_message('<div class="message-inner" style="padding:15px;">' . $message . '</div>' );

}

```

This is not working, It says array to string conversion, form and formstate is undefined something like this. I know this is not correct way please suggest me the correct way to print values in dropdown.

# Answer
> 3 votes
Assuming testing() is a page callback, you want this:

```
function testing()
{
  $form = drupal_get_form('cart_confirmation_form')
  $output = '<div class="popup-related-tabs" style="float: left;" >' . render($form) . '</div>';

  return $output;
}

```

Though personally I'd built it as a render array:

```
function testing()
{
  $page = array
  (
    '#prefix' => '<div class="popup-related-tabs" style="float: left;" >',
    '#suffix' => '</div>',
    'form' => drupal_get_form('cart_confirmation_form')
  );

  return $page;
}

```

# Answer
> 0 votes
Above answer also true but you can also do very easily using drupal\_render like this

`function testing()
{
 $output = drupal_render(drupal_get_form('cart_confirmation_form'));
 return $output;
}`

---
Tags: 7, forms
---


title: Render a link from a FieldPluginBase

text:
# Question
Title: Render a link from a FieldPluginBase
I created a custom view field with the hook \_views\_data and a custom Class who extends FieldPluginBase.

With the render method, I can return a sample string :

```
class MyCustomClassViewsField extends FieldPluginBase {
...
    public function render(ResultRow $values) {
      $node = $values->_entity;
      return $node->id(); // My view field shows the nid of the current node
    }
...

```

Now, I want shows a link with my field. I tried :

```
class MyCustomClassViewsField extends FieldPluginBase {
...
    public function render(ResultRow $values) {
      $node = $values->_entity;
      return "<a href='http://www.test.com'>custom link</a>"
    }
...

```

But my field in my view shows :

```
<a href='http://www.test.com'>custom link</a>

```

and not

custom link

How can I show the link as an html element, not a sample text ?

Thank you =)

**UP**

This code work :

```
return array('#markup' => \Drupal::l("test",\Drupal\Core\Url::fromUri("http://www.example.com")));

```

ut the l() function is deprecated. If I use Link::fromTextAndUrl instead :

```
return array('#markup' => \Drupal\Core\Link::fromTextAndUrl("test",\Drupal\Core\Url::fromUri("http://www.example.com")));

```

I get the error :

> \[Sun Sep 18 22:17:59.444188 2016\] \[:error\] \[pid 2143\] \[client 192.168.1.48:53322\] Recoverable fatal error: Object of class Drupal\Core\Link could not be converted to string in /var/www/xxxxx/core/lib/Drupal/Component/Utility/Xss.php on line 67, referer: https://192.168.1.45/admin/structure/views/view/customview
>
> \[Sun Sep 18 22:17:59.446098 2016\] \[:error\] \[pid 2143\] \[client 192.168.1.48:53322\] PHP Fatal error: Uncaught Error: Call to a member function get() on null in /var/www/xxxxx/core/lib/Drupal/Core/Session/SessionHandler.php:76\nStack trace:\n#0 /var/www/xxxxx/vendor/symfony/http-foundation/Session/Storage/Handler/WriteCheckSessionHandler.php(89): Drupal\Core\Session\SessionHandler-\>write('BTaHaVF0t-bMk2Z...', '\_sf2\_attributes...')\n#1 /var/www/xxxxx/core/lib/Drupal/Core/Session/WriteSafeSessionHandler.php(75): Symfony\Component\HttpFoundation\Session\Storage\Handler\WriteCheckSessionHandler-\>write('BTaHaVF0t-bMk2Z...', '\_sf2\_attributes...')\n#2 /var/www/xxxxx/vendor/symfony/http-foundation/Session/Storage/Proxy/SessionHandlerProxy.php(77): Drupal\Core\Session\WriteSafeSessionHandler-\>write('BTaHaVF0t-bMk2Z...', '\_sf2\_attributes...')\n#3 \[internal function\]: Symfony\Component\HttpFoundation\Session\Storage\Proxy\SessionHandlerProxy-\>write('BTaHaVF0t-bMk2Z...', '\_sf2\_attributes...')\n#4 \[internal function\]: session\_write\_close()\n#5 {main}\n thrown in /var/www/xxxxx/core/lib/Drupal/Core/Session/SessionHandler.php on line 76, referer: https://1xxxxx/admin/structure/views/view/customview

How can I replace the l deprecated function ?

# Answer
> 2 votes
You need to convert array to string to show it as link. May this works for you.

```
class MyCustomClassViewsField extends FieldPluginBase {
...
    public function render(ResultRow $values) {
      $node = $values->_entity;
$title = 'Custom Link';
$url = \Drupal\Core\Url::fromUri('http://www.test.com');
$link = \Drupal\Core\Link::fromTextAndUrl($title, $url)->toString();

      return $link;
    }

```

---
Tags: views, 8, entities
---


# Question
Title: Hide 'previous' on first and 'next' on last image in views slideshow
I create slideshow using Views Slideshow module, controls are enabled (previous, next), I enable and 'End slideshow after last slide' in settings.

Now, how I can hide 'previous' text on first image in slide and 'next' text on the last image in slide?

# Answer
I resolve problem using jQuery, there is code that I use in my case:

```
jQuery(document).ready(function($){

function Left() {
    if ($('#views_slideshow_cycle_div_slide-block_1_0').css('display') == 'block') {
    $("#views_slideshow_controls_text_previous_slide-block_1").css({"visibility": "hidden"});
}
else {
$("#views_slideshow_controls_text_previous_slide-block_1").css({"visibility": "visible"});
}
};

function Right() {
    if ($('#views_slideshow_cycle_div_slide-block_1_2').css('display') == 'block') {
    $("#views_slideshow_controls_text_next_slide-block_1").css({"visibility": "hidden"});
}
else {
$("#views_slideshow_controls_text_next_slide-block_1").css({"visibility": "visible"});
}
};

window.setInterval(function(){
    Left();
    Right();
}, 10);

});

```

Because 'previous' is visible until page is fully loaded and then disappear, I add to css:

```
#views_slideshow_controls_text_previous_slide-block_1 {
   visibility: hidden;
}

```

There is one problem, in example above 'block\_1' is views slideshow block, number after '\_0' tell that is first slide item and '\_2' tell that is third item, so you must change '\_2' every time when is number of slide items is changed. For me that code resolve problem because I have only three images in slide and that wasn't ever change.

Maybe someone have better solution or can help fix this problem?
> 0 votes

# Answer
Easiest way out is to use css. Hide the control when you don't need it.The particular element can be found by a simple inspection. Hope it helps.

```
display:none;

```

Another alternative is to use the slideshow API to customise the behaviour. You can start here.
> 1 votes

# Answer
In case someone is still looking for it's solution then here it is. First you need to add **json2** library with json2.js file inside it. This will give jQuery Cycle Custom Options in your slideshow settings. There under the Advanced options select **after** and under Advanced option value add following script:

```
var index = options.currSlide;
    $('#prev')[index == 0 ? 'hide' : 'show']();
    $('#next')[index == options.slideCount - 1 ? 'hide' : 'show']();

```

Here prev and next are your ids. Update Advanced options and you are good to go.
> 0 votes

---
Tags: views
---


# Question
Title: D8: Cannot redirect user at onKernelRequest event
I want to redirect the user at "onKernelRequest" event and I have this method:

```
  public function onKernelRequest($event) {
    // Restricts access to nodes (views/edit).
    if (!empty($event->getRequest()->attributes->get('node'))) {
      $nid = $event->getRequest()->attributes->get('node')->get('nid')->getValue()['0']['value'];
      if (!$this->accessCheckService->canUserAccessByNodeId($nid)) {
        $response = new RedirectResponse('/access-restricted-by-taxonomy-term');
        $response->send();
        return;
      }
    }

```

The response is being sent, but the user is not redirected to the given address (access-restricted-by-taxonomy-term). It seems that RedirectResponse takes no action at onKernelRequest event. How can I fix this?

# Answer
Instead of sending the response yourself you can try to use the method `setResponse()` of `$event`:

```
$event->setResponse($response);

```
> 2 votes

---
Tags: 8, redirection
---


# Question
Title: Create a reference all available block content
In Drupal 7 there is **Block Reference** field module that can reference pretty much all available blocks, including views' blocks, system blocks, menu blocks etc.

I'm just starting with Drupal 8 and since the Block Reference module doesn't have a version for it, and the built-in Entity Reference doesn't seem to pick up views' blocks, system blocks, I want to create a new custom block type. In this new block type, I want to have a reference field that can reference all available block content.

Is there a way to do it?

# Answer
Like I said, I'm new to Drupal 8 so not familiar with new rule and features. After a bit digging here is what I found out.

Entity Reference field allows to reference block instances (config) or custom blocks (content).

Before I was set my field to **Content \> Custom block**, now I switch it to **Configuration \> Block** then you have to **Place the block** that you want to reference to, even if it is in disabled. After that, you can have your Entity Reference field pick that up otherwise it won't show.

You can have a look at here for more detail.
> 6 votes

# Answer
To fix the restricted access: make a region in yourtheme.info. Don't render the region in your page.html.twig. Place the config block in that region.
> 3 votes

---
Tags: 8, entities
---


# Question
Title: Rewrite a text field in "Manage display" of content type
This feels like it should be simple to do, but I can't work it out.

If I have a text field, how do I rewrite the output of the field on the "Manage display" tab of the content type? For example, I might want to add units, or convert a product ID into a link to an external website.

I know how to do this stuff in Views, but it would seem to make sense to be able to do it via the "Manage Display" tab for a content type. Am I missing something?

# Answer
You can achieve this by creating `field.html.twig`.

Default theme implementation for a field.

You will get more information:

Override field template (twig)

field.html.twig and field--node--title.html.twig
> 2 votes

# Answer
You have a couple of choice based on your needs:

1. Overriding the template file (twig) of the specific field
2. Using form\_hook\_alter
3. For complex and clean solution I suggest you to use a custom widget for your field type.
> 2 votes

---
Tags: nodes, 8, entities
---


# Question
Title: How to embed view in basic page content?
I want to embed a view in content of type basic page in D8. How to I do that. Insert View module is still not stable to be used in D8.

# Answer
> 2 votes
You might want to have a look at Paragraphs and some of the new Views Reference fields. You could then intersperse Views and content.

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

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

# Answer
> 0 votes
You can use views\_embed\_view() function

```
\Drupal::service('renderer')->render(views_embed_view('VIEW_NAME'));

```

Where VIEW\_NAME is the name of your view.

---
Tags: views, 8
---


title: Not all the buttons are displayed

text:
# Question
Title: Not all the buttons are displayed
I installed CKEditor plugin ver. 1.16. In configuration page for editor appearance I selected "Full":

But when I open "Add content" page I see the different picture:

When I changed the appearance from "Full" to "Advanced", the appearance doesn't change. But when I switched to "Basic" appearance, it worked.

What's the issue here? Why not all the buttons are displayed?

# Answer
On 'Add content' page, please check which '**Text format**' you have selected in drop-down below the CKEditor.

Make sure that you have selected the **Full HTML** or **Filtered HTML** according to your field settings.
> 0 votes

---
Tags: wysiwyg
---


title: Using the right t()

text:
# Question
Title: Using the right t()
In Drupal 8, it seems as though object-oriented code is encouraged to use `$this->t()` instead of the global function `t()`, by either adding `StringTranslationTrait` to the class, or extending a core class (eg. a plugin, controller or form) that has it.

If I understand correctly, this is to encapsulate localization and eg. translate particular objects to specific languages without affecting the global scope?

I have a particular subform that occurs both as part of a full form (in a routing path) and as part of a Filter plugin's settings. To accomplish this, I made the subform builder a static function inside the main form, allowing the filter plugin to call it directly. (Both the settings form and the main form add other fields in addition to the subform.)

Now, even though the subform function is static, it's only invoked in one of two non-static contexts (extended from FilterBase and ConfigFormBase, respectively, both of which inherit the StringTranslationTrait).

It seems as though the right thing here is to pass the caller's object to the static function, and then use that caller's t() function.

Call 1:

```
  public function buildForm(array $form, FormStateInterface $form_state) {
[...]
    $form = self::buildFormHandlers($form, $defaults, $this);

```

Call 2:

```
  public function settingsForm(array $form, FormStateInterface $form_state) {
[...]
    $form = XBBCodeHandlerForm::buildFormHandlers($form, $this->tag_settings, $this);

```

Definition:

```
  public static function buildFormHandlers(array $form, array $defaults, $caller) {
    // Add form fields:
[...]
      '#title' => $caller->t('Tag settings'),

```

It looks like a weird pattern, though, so I'm wondering if I'm missing the point, or overthinking it.

# Answer
> 1 votes
There's no right or wrong `t` because at the end of the day you end up using the translate method of the `string_translation` service. Passing around objects are pretty pointless because the `StringTranslationTrait` and `t` both execute the exact same code: `\Drupal::service('string_translation')->translate($string, $args, $options)`. The call chain is different of course but at the end of the day, that's the exact call they both run.

# Answer
> 2 votes
As @berdir said in Using the right t(), the recommended way is passing the StringTranslation service.

However the use of a static method there (`public static function buildFormHandlers`) is a smell to me that this could be moved to a different helper service injected in both forms, or that you should create a trait yourself used in both.

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


title: Debugging JavaScript tests

text:
# Question
Title: Debugging JavaScript tests
Recently started working on some JavaScript tests by extending JavascriptTestBase in drupal 8.2 and the biggest problem currently is debugging.

Phantomjs is installed and i have no problem running JavaScript tests. Xdebug is installed too.

```
$this->getSession()->getScreenshot();

```

is not returning any output, maybe some additional configuration is needed?

```
file_put_contents('/Users/me/debug.html', $this->getSession()->getDriver()->getHtml('/html/body'))

```

is giving me a half broken page.

I would really appreciate if someone can share how they debug these tests and how they set it up, some useful links. The biggest help would be to be able to take screenshots but any info on this topic is welcome.

# Answer
> 2 votes
I think that you are looking for JavascriptTestBase::createScreenshot() https://api.drupal.org/api/drupal/core!tests!Drupal!FunctionalJavascriptTests!JavascriptTestBase.php/function/JavascriptTestBase%3A%3AcreateScreenshot/8.2.x

See the following snippet from a core test:

```
  /**
   * Tests creating screenshots.
   */
  public function testCreateScreenshot() {
    $this->drupalGet('<front>');
    $this->createScreenshot('public://screenshot.jpg');
    $this->assertFileExists('public://screenshot.jpg');
  }

```

---
Tags: 8, javascript, debugging, testing
---


title: Drush 5 & 8 side-by-side

text:
# Question
Title: Drush 5 & 8 side-by-side
Is it possible have version 5 & 8 of Drush installed and to use a preferred version?

I am running an ubuntu server on which I have Drush5 installed. My attempts to remove is results in the following:

```
sudo apt-get autoremove drush -y
Reading package lists... Done
Building dependency tree
Reading state information... Done
You might want to run 'apt-get -f install' to correct these:
The following packages have unmet dependencies:
 linux-image-extra-3.13.0-91-generic : Depends: linux-image-3.13.0-91-generic but it is not going to be installed
 linux-image-extra-3.13.0-95-generic : Depends: linux-image-3.13.0-95-generic but it is not going to be installed
 linux-image-generic : Depends: linux-image-3.13.0-95-generic but it is not going to be installed
E: Unmet dependencies. Try 'apt-get -f install' with no packages (or specify a solution).

```

All attempts to deal with that issue have been unsuccessful.

So, I'm just wondering if both versions can be installed and used independently?

# Answer
> 2 votes
Yes.

```
alias drush5='~/drush5/drush'
alias drush6='~/drush6/vendor/bin/drush'
alias drush7='~/drush7/vendor/bin/drush'
alias drush8='~/drush8/vendor/bin/drush'

```

You will get help from Switching Drush Versions.

---
Tags: drush
---


# Question
Title: Term reference is not available as a contextual filter for a View. Why not?
I have a commerce product of type Album. On this content type is a taxonomy term reference. This term is from the vocabulary 'Our Artist'. In other words, every album gets tagged w/ the artist name that comes from the 'Our Artists' vocabulary.

I'm trying to create a view that groups together all of an artist albums. I want to use this taxonomy term as a contextual filter. But it is not showing up as an option in the contextual filters list. Can someone explain why?

# Answer
As mentioned in Niall's comment, you will want to add the taxonomy relationship. In a view that I created recently, I used the `Content: Taxonomy terms on node` relationship. Once I added it, `Content: Has taxonomy term` became an available option under **Filter criteria**.

That is only one way of doing it. There are a few different taxonomy relationships which serve unique purposes. I'd experiment with them to see what fits your needs.
> 1 votes

---
Tags: views
---


# Question
Title: Safe to add a class attribute to the HTML element via the theme?
In Drupal 8 is it safe to manually add a class attribute to the HTML element in the theme's html.html.twig file?

```
<html{{ html_attributes }} class="no-js">

```

Its working fine for me but I don't know if there are some instances where Drupal would want to add a class as part of html\_attributes? If so then presumably my output would be this:

```
<html class="drupals-class" class="no-js">

```

# Answer
> 2 votes
You should use `.addclass()`:

```
<html{{ html_attributes.addClass('no-js') }}>

```

That would prevent the output in the example from your question and the result will be:

```
<html class="drupals-class no-js">

```

---
Tags: theming, 8
---


# Question
Title: Get() on array in settings from custom Form controller
I'm making a custom module with a form controller, that has a text\_format field. I'm storing the text\_format value in my submitForm function like so.

```
public function submitForm(array&$form, FormStateInterface $form_state) {
    $this->config('foundation.settings')
         ->set('infoblock_text', $form_state->getValue('infoblock_text'))
        ->save();
}

```

I'm attempting to retrieve that for the default value of the field like so

```
    $form['infoblock_text'] = [
        '#type'          => 'text_format',
        '#title'         => t('Infoblock text'),
        '#description'   => t('The body text for the infoblock on the front page'),
        '#format'        => 'full_html',
        '#default_value' => $config->get('infoblock_text'),
    ];

```

However it's empty. After performing a die(print\_r($config-\>get('infoblock\_text'))) I found that infoblock\_text is actually an array and 'value' is the key that contains the text I need. This is what the die() statement returns

```
Array ( [value] =>
Text of infoblock
[format] => full_html ) 1

```

After seeing that I actually needed to retrieve the value element rather the entire array I attempted the following with no luck.

```
$config->get('infoblock_text', 'value');
$config->get(['infoblock_text', 'value']);
$config->get('infoblock_text')->value;
$config->get('infoblock_text')->value();
$config->get('infoblock_text')->getValue();
$config->getValue('infoblock_text');
$config->getValue('infoblock_text');
$config->getValue('infoblock_text');

```

So how would I actually retrieve the value of 'infoblock\_text', when $config-\>get('infoblock\_text') returns the entire array?

# Answer
You can handle the config like an array:

```
$form['infoblock_text'] = [
    '#type'          => 'text_format',
    '#title'         => t('Infoblock text'),
    '#description'   => t('The body text for the infoblock on the front page'),
    '#format'        => isset($config->get('infoblock_text')['format']) ? $config->get('infoblock_text')['format'] : 'full_html',
    '#default_value' => isset($config->get('infoblock_text')['value']) ? $config->get('infoblock_text')['value'] : '',
];

```

When accessing the array like this, it's always a good idea to check if the key is set. This avoids warnings in your log.
> 2 votes

---
Tags: forms, 8
---


# Question
Title: Are deleted entities automatically excluded from entity queries?
I'm trying to figure out if deleted entities are automatically excluded from entity queries. IE, if I did:

```
$num = \Drupal::entityQuery('my_entity')->count()->execute();

```

Would the number of entities found go down if I deleted one through the ui? How could I include/exclude deleted entities in this query?

# Answer
Deleted entities are not excluded because they are *gone*. They can't be excluded nor included as they do no longer exist in the database.

So they can also not be counted anymore.

This might change during 8.x, as there is work going on for archiving/putting them into trash instead of actually deleting. The details of that and how that affects entity queries are still being discussed.
> 2 votes

---
Tags: 8, entities
---


# Question
Title: Custom module to alter display value of field
I have a question about custom modules. I am trying to write a module that changes the display value of a field. I think the thing I'm trying to do require a

```
hook_page_alter

```

method, and to change the field

```
$page['content']['system_main']['nodes'][$nid]['body']

```

So far I'm haven't been able to change anything on the page. Would anyone have a good solution?

# Answer
The example you're using in the `hook_page_alter()` docs isn't a valid example but a demonstration. The problem here is the variable `$nid` isn't defined in your hook invocation. The expression:

```
$page['content']['system_main']['nodes'][$nid]['body']

```

isn't valid. `$page['content']['system_main']['nodes']` contains an associated array of nid/node data.

This can be one or many nodes depending on the context (e.g. front page vs. a node page). You'll need build your logic accordingly (e.g. `$nid = reset($page['content']['system_main']['nodes']`) to retrieve the specific node that you want then make the altercation as you need it.
> 0 votes

---
Tags: 7, theming
---


title: hook_menu() to display node view mode

text:
# Question
Title: hook_menu() to display node view mode
How to create hook\_menu to display node view mode?

node/% - full view mode (default)

node/%/subpage - custom created view mode of this node, for example "subpage"

I've tried this: How to render custom view mode in d7 but it doesn't work. Maybe something is wrong with the code?

# Answer
There is a module exists that does just that: View Mode Page.

Check it out and inspect the source to see how it works.
> 1 votes

---
Tags: 7, routes
---


title: Let users create versions of articles

text:
# Question
Title: Let users create versions of articles
Let's say I want to make a wiki-styled knowledge base for recipes.

*User A* submits a recipe for "Lasagna". *User B* likes this recipe but would like to submit her grandmothers special recipe for others to enjoy, so she clicks "post your version" and then writes "Lasagna - Grandma B's style". The two articles now automatically have a relationship, but behave as independent pieces of content.

*User C* knows he wants Lasagna, and would like to try a new version of it. This is where I would like all the recipes relating to Lasagna can be listed and sorted on things like points (thumbs up/down), number of comments, visits etc.

If I had complete control over the terms this wouldn't be hard to do with views and taxonomies, but I want this to be community driven and versions of content and their relations to happen organically.

How would you approach this? I've tried References but I couldn't get it to cross reference. Relation seems to be very close, but how would I create the "post your version" (i.e relation) button?

# Answer
> 0 votes
A simple solution might be to something like Rules, and Rules Link.

Create a rule that clones the data from one node into a new node. Have it actioned to happen when a certain link/button is clicked (hence, Rules Link). The last set of actions in the rule would be to set an entity reference back to the original node (or set a common taxonomy term)

Otherwise, create a small custom module that basically does the same thing. mapping fields onto each other and creating a new node. You'll have more control on what happens with the data but its not easy if you are not a developer.

---
Tags: nodes
---


# Question
Title: How to define an entity type within entity_get_info()
Is it possible to define your own entity type so that a call to entity\_get\_info() returns your new type?

# Answer
> 0 votes
I found it. You use the hook\_entity\_info() hook.

https://www.drupal.org/node/1026420

---
Tags: 7, entities
---


# Question
Title: How to unsubscribe from issues on drupal.org to not see the updates in my dashboard?
I visit My dashboard to see answers on my issues. This is comfortable.

I've been typed comments in other issues and got the answer, but now I receive the info about new comments on those issues that I do not want to look. I get the "updated" tag on them.

How to kick those issues from My Dashboard https://www.drupal.org/dashboard?

# Answer
You can unfollow the post by clicking on following.
> 0 votes

---
Tags: community-official-site
---