# Question
Title: Remove Home from menu at module installation
I can remove the "Home" tab from the main menu going to `/admin/structure/menu/manage/main`, but I would like to automate it so that it is done at module installation. I checked that the configuration is saved in `core.menu.static_menu_link_overrides.yml`, but I cannot put it in `config/install` since it defines pages created by core. As a matter of fact, I should set `enabled=false` in the already existing `page standard__front_page`; how can I do that at module installation?

# Answer
> 0 votes
Following the suggestion from @Leigh Mason and copying almost verbatim from the link he posted, I ended up implementing `hook_install()`:

```
function hook_install() {
  $menu_link_manager = \Drupal::service('plugin.manager.menu.link') ;
  $front_page_link = $menu_link_manager->getDefinition('standard.front_page') ;
  $front_page_link['enabled'] = 0 ;
  $menu_link_manager->updateDefinition($menu_id, $front_page_link) ;
  $cache = \Drupal::cache('menu') ;
  $cache->deleteAll() ;
}

```

and the link was successfully deleted. I think that the last two lines are not really needed, I will check it at the next build from scratch...

---
Tags: 8, navigation
---


# Question
Title: How do I automatically generate image styles?
How do I automatically generate different image styles in Drupal 8, for existing images?

For example, I have about 10K images in field\_image field. I would like to generate thumbnails using my thumbnail image style for those images.

# Answer
Image derivatives will be automatically generated once requested and not-yet existing.

But if you are asking how to programmatically create image derivatives checkout `ImageStyle::createDerivative`.

Here's a sample snippet were I did exactly that:

```
$field_name = 'field_my_image';
$image_style_name = 'my_image_style';
$image = [];

// Get the original image URI.
$original_image = $node->{$field_name}->entity->getFileUri();

// Load the image style.
$style = \Drupal::entityTypeManager()
  ->getStorage('image_style')
  ->load($image_style_name);

// Get the styled image derivative.
$destination = $style->buildUri($original_image);

// If the derivative doesn't exist yet (as the image style may have been
// added post launch), create it.
if (!file_exists($destination)) {
  $style->createDerivative($original_image, $destination);
}

// Do whatever else you need to do.
$image['url'] = file_url_transform_relative($style->buildUrl($original_image));
$properties = $node->{$field_name}->first()->getValue();
$image['alt'] = $properties['alt'];
$image['title'] = $properties['title'];

```
> 12 votes

---
Tags: 8, media
---


# Question
Title: Finding entity/webform fields in the database
A bunch of user accounts were deleted and recreated with new UIDs, and so any webform submissions or entities that have fields pointing to the old UID are now broken/wrong. I already updated some UID columns to the new UID, but now I need to find other tables/fields that still point to the old UIDs (and the columns aren't called "UID").

Given the ID of an entityform or webform submission, how can I find which tables/columns in the database correspond to the fields that make up that entityform or submission?

As an example, say I have an entityform with entityform\_id = 123 and type = 'my\_report'. If I view the entity using the Drupal interface, I see a user field that is blank, because it points to a user's old UID. How do I find where that field is located in the database? Is there a mapping from type 'my\_report' to a list of fields or tables?

Also of note is that I need to do this for a decent amount of types of entityforms and webforms, so it'd be nice if I could query for them all, rather than looking at each field of each form using the interface or something.

# Answer
> 0 votes
I used a query similar to this to help me find a list of tables and columns I needed to update:

```
SELECT DISTINCT
    table_name,
    column_name
FROM
    INFORMATION_SCHEMA.COLUMNS
WHERE
    column_name LIKE '%user%_target_id'
    AND (table_name LIKE 'field_data_field%'
    OR table_name LIKE 'field_revision_field%')

```

It's not ideal, and it still missed a couple tables.

I put the resulting list of tables and columns into a Python script and generated the SQL update statements I needed to run.

There is probably a better way to do it.

---
Tags: 7, entities, database, webforms
---


title: Avoid duplicate files on migrate update

text:
# Question
Title: Avoid duplicate files on migrate update
I am creating file entities with migrate using drush. Image files are being copied down from a remote server. I tried

```
$this->addFieldMapping('file_replace')->defaultValue('FILE_EXISTS_REPLACE');
$this->addFieldMapping('preserve_files')->defaultValue(TRUE);

```

If I run the migration with --update it duplicates the files, not replacing existing ones.

```
drush mi DAProductImages --limit="10 items" --update

```

When I run this first time it creates the files. Second time it adds \_0 to the filenames and duplicates the files. If I rollback after first migration the files are being removed. When rolling back after the second migration only files of last batch get removed. I also tried with:

```
$this->addFieldMapping('preserve_files')->defaultValue(FALSE);

```

How can I make it so that I will not end up with duplicates? I have about 30000 images so I cannot afford that.

# Answer
This solved it for me.

The documentation at this link was missing a mention that you need to use the class prefix - I just submitted an update to the Drupal Docs to make it more clear:

```
$this->addFieldMapping('preserve_files')
  ->defaultValue(1);

$this->addFieldMapping('file_replace')
  ->defaultValue(MigrateFile::FILE_EXISTS_REUSE);

```
> 2 votes

# Answer
This works:

```
$this->addFieldMapping('field_document', 'field_document_uri');
$this->addFieldMapping('field_document:file_replace')->defaultValue(MigrateFile::FILE_EXISTS_REUSE);

```

Found here.
> 0 votes

---
Tags: migrations
---


# Question
Title: Show if a user is online, idle, or offline on their account page?
I want to display the status of the user on the account page. I added the following code in the theme I am using. It works, but users are never displayed offline.

Why? What is wrong in the code?

### user.html.twig

```
<div class="bs-field-status">
  {% if status == 'Online' %}
    <i class="user-online fa fa-circle fa-lg"></i> Online
  {% elseif status == 'Absent' %}
    <i class="user-absent fa fa-circle fa-lg"></i> Absent
  {% else %}
    <i class="user-offline fa fa-circle fa-lg"></i> Offline
  {% endif %}
</div>

```

### bootstrap\_subtheme\_front\_office.theme

```
<?php
/**
 * @file
 * Bootstrap sub-theme.
 *
 * Place your custom PHP code in this file.
 */

use Drupal\Core\Database\Database;

/**
 * Implements hook_entity_presave().
 */
function bootstrap_subtheme_front_office_preprocess_user(&$variables) {
  // get user object
  $user = $variables['elements']['#user'];
  //- The user has logged in at least once
  if ($user->getLastLoginTime()) {
    if (account_is_logged_in_less_then_thirty_minutes($user->id())) {
      $status = 'Online';
    }
    else {
      $status = 'Absent';
    }
  }
  else {
    $status = 'Offline';
  }
  $variables['status'] = $status;
}

/**
 * @param $uid
 *
 * @return bool
 */
function account_is_logged_in_less_then_thirty_minutes($uid) {
  $connection = Database::getConnection();
  $query = $connection->select('sessions', 'sessions')
    ->fields('sessions', ['sid', 'uid', 'timestamp'])
    ->condition('sessions.uid', $uid, '=')
    //- chef if the user was online in 30 minutes (60 * 30)
    ->condition('sessions.timestamp', \Drupal::time()
        ->getRequestTime() - (60 * 30), '>')
    ->execute();
  //- Get result.
  $results = $query->fetchAll(\PDO::FETCH_OBJ);
  return (count($results) > 0) ? TRUE : FALSE;
}

```

# Answer
> 1 votes
I guess the problem lies here, for starters:

```
//- The user has logged in at least once
  if ($user->getLastLoginTime()) {
    if (account_is_logged_in_less_then_thirty_minutes($user->id())) {
      $status = 'Online';
    }
    else {
      $status = 'Absent';
    }
  }
  else {
    $status = 'Offline';
  }

```

The `if ($user->getLastLoginTime()) {` will be TRUE always, after the user has logged in once. This will prevent the `else` from ever being hit, thus, 'Offline' never gets set.

I don't know what the difference is for you in terms of time between "Absent" or "Offline", but it sounds like you'd want to figure another calculation here to know what to set status to.

This can be simplified to:

```
function bootstrap_subtheme_front_office_preprocess_user(&$variables) {
  // get user object
 $user = $variables['elements']['#user'];

 $last = $user->getLastAccessedTime();
 $now = \Drupal::time()->getRequestTime();

 switch ($last) {
   case ($last > ($now - 900)) :
     $variables['status'] = 'Online';
     break;
   case (($last < ($now - 900)) && $last > ($now - 1800)) :
     $variables['status'] = 'Absent';
     break;
   default:
     $variables['status'] = 'Offline';
     break;
 }
}

```

Then break down smaller functions to evaulate the time against how many minutes ago they were active... use it in the switch above.

`getLastAccessedTime()` does:

> The timestamp when the account last accessed the site.
>
> A value of 0 means the user has never accessed the site.

So you don’t need a `db_select`.

# Answer
> 1 votes
The ultimate problem with Drupal and user status is cache, but here is some code I am working with.

```
if ($variables['accessTime'] > (intval(time()) - 800)) {
  $variables['sessionState'] = 'active';
}
else {
  $variables['sessionState'] = 'inactive';
}

```

Then in Twig you can do stuff like:

```
{% if sessionState == active %}

{% endif %}

```

or

```
{%
  set activeClass = [
    sessionState == 'active' ? 'Active' : 'Not Active'
  ]
%}

```

# Answer
> 1 votes
As Prestosaurus in their answer already said, the biggest issue here is cache. What's been done in preprocess hooks will be cached until you flush Drupal's theme cache the next time. You'll need to ensure the cache gets busted by reducing the max age of your piece of markup or by ajaxifying it completely.

---

I just created User Online Status. This module contains a new pseudo field for user entities, a route to return a given user's online status as a non-cached JSON response, and some JS that checks that response and prints the online status into the pseudo field.

It still needs proper description, screenshots and tests, though.

1. Download and enable the module.
2. Go to http://d8.localhost/user/1 to see the online status of user 1.

Optionally: Go to http://d8.localhost/admin/config/people/accounts/display to adjust the "Online Status" field's weight.

---

Credits for the `switch` snippet to Kevin (answer).

---
Tags: 8, theming, users
---


# Question
Title: Migrate Private Files: FILE_EXISTS_REUSE still duplicate files
I'm trying to migrate private files (file migration), the problem is even I set file\_replace to 'FILE\_EXISTS\_REUSE' the files are still duplicated (it adds \_1 or \_2, and so on.). Here is my mapping:

```
    $this->addFieldMapping('file_replace')
         ->defaultValue('FILE_EXISTS_REUSE');
    $this->addFieldMapping('preserve_files')
       ->defaultValue(FALSE);

```

Please help!

# Answer
> 1 votes
This solved it for me. The documentation at this link has been updated to show that you need to use the class prefix:

```
$this->addFieldMapping('preserve_files')
  ->defaultValue(1);

$this->addFieldMapping('file_replace')
  ->defaultValue(MigrateFile::FILE_EXISTS_REUSE);

```

# Answer
> 0 votes
Maybe try:

```
$this->addFieldMapping('field_name', 'field_name');
$this->addFieldMapping('field_name:file_replace')->defaultValue(MigrateFile::FILE_EXISTS_REUSE);

```

---
Tags: files, migrations
---


# Question
Title: .htaccess error on local site in docksal
I've built a Drupal 8.6.4 website within Acquia Dev Desktop, but moved it into a local Docker/Docksal setup to continue working (haven't used it before) - on a mac, if it matters. Everything seems fine, but for two issues. The first is a bunch of Security warnings in the logs about htaccess, saying to add an htaccess containing some specific code to the "/var/www/config/default" directory, but I don't have this file directory. It's a Docksal set-up: just ~/projects/projectname/docroot set-up on my computer.

The second issue, which I suspect may be related, is that I can't Drush archive-backup --destination=x/x/x.. It always tells me the file permission prevents it, Even if I give full read/write permission on the folder. But I can do it without the --destination added. It just puts it in a temp folder.

Here's the Error I see - it generates most any time I load an admin page.

```
    Security warning: Couldn't write .htaccess file. Please create a .htaccess file in your /var/www/config/default directory which contains the following lines:
    # Deny all requests from Apache 2.4+.
    <IfModule mod_authz_core.c>
      Require all denied
    </IfModule>

    # Deny all requests from Apache 2.0-2.2.
    <IfModule !mod_authz_core.c>
      Deny from all
    </IfModule>

    # Turn off all options we don't need.
    Options -Indexes -ExecCGI -Includes -MultiViews

    # Set the catch-all handler to prevent scripts from being executed.
    SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
    <Files *>
      # Override the handler again if we're run later in the evaluation list.
      SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003
    </Files>

    # If we know how to do it safely, disable the PHP engine entirely.
    <IfModule mod_php5.c>
      php_flag engine off
    </IfModule>

```

# Answer
There is a directory in the root of the Acquia project, `config/default`.So, all you need it's make it writable.

or you can change `$config_directories['vcs']` and `$config_directories['sync']` in your `settings.php` to somewhere which will be writable .
> 1 votes

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


# Question
Title: Remove "No front page content has been created yet"
How can I remove default system message like "No front page content has been created yet" in Drupal 8?

I've tried below method but is doesn't work.

```
function MYTHEME_preprocess_page(&$vars) {

  // Remove the "No front page content has been created yet.".
  if (isset($vars['page']['content']['system_main']['default_message'])) {

    unset($vars['page']['content']['system_main']['default_message']);
  }
}

```

# Answer
There are many possible solutions for this problem, but here are a few of the more straightforward ones:

1. Edit the **Frontpage** view at /admin/structure/views/view/frontpage as follows:

This View form allows you to adjust the out-of-the-box front page. In the **NO RESULTS BEHAVIOR** section, click on the **Global: Unfiltered text** item. This will open a dialog box to edit that setting. From here you can see that this is where the undesirable message is coming from. Click on the **Remove** link beside the bottom buttons to remove that message. Depending on the desired front page behavior, you may also want to remove one or both of the other items listed under **NO RESULTS BEHAVIOR**.

Once you've removed the unwanted items, be sure to click the **Save** button on the View form to make those changes permanent. You can then browse to the front page and see the results. (You might need to **Clear all caches** at /admin/config/development/performance to see the change)

2. Or, create a custom front page:

Create new content of type **Basic Page**. Give it the title you want your front page to have. For the body, you can leave it blank, or put whatever static content you want to always appear on the front page. After saving and publishing this new content, write down the "**/node/some-number**" part of the URL.

You can now set this new node as the front page at /admin/config/system/site-information by changing the **Default front page** setting to the **/node/some-number** you wrote down earlier. Save the settings and things should be all set.

3. To do it programmatically, you might add this code to your custom theme or module

`use Drupal\Views\ViewExecutable;`

```
// Implements hook_views_pre_render().
function MY_THEME_OR_MODULE_NAME_views_pre_render(ViewExecutable $view) {
  if($view->id() == 'frontpage' && $view->current_display == 'page_1') {
    // Use some or all of the following 3 lines to remove specific
    // 'no results' behaviors
    unset($view->empty['area_text_custom']);
    unset($view->empty['node_listing_empty']);
    unset($view->empty['title']);
  }
}

```

or you could use `$view->empty = [];` instead of the 3 separate `unset()`'s to remove all "no results" behaviors from the frontpage view. Note that this code assumes you haven't changed the view's name or display name from the defaults. If this is not so, the if() statement will require some tweaking.
> 18 votes

# Answer
In Drupal 8, in Structure / Views / Edit the FrontPage and in the Page Settings / no Results Behavious Section: Click to edit each item and click 'remove' (NOTE: in the "No Results Behaviour" only)
> 2 votes

---
Tags: 8, theming
---


# Question
Title: How to access private page (views page) with authentification in the URL?
All the pages of my site are private (by role). I have nodes and views pages. I want to access to a views page with an external link. But, If the visitor isn't logged, this visitor can't access to the page.

Is there a solution to specify a token or the login / pass in the URL to automaticaly access to the page?

# Answer
Try reading about these projects:

They're not all usable but you can get inspired by their different features and how they implement them so you can solve it for your own problem.
> 0 votes

---
Tags: tokens
---


title: How do I manually group content?

text:
# Question
Title: How do I manually group content?
I have created a wishlist in which those nodes are showing which are flagged, Wishlist working fine

The next task is to create favorite groups. That is, the user must be able to create groups of favorites, being able to edit a name, for example “summer recipes”, and assign recipes to the group.

What i have tried so far i have created a another content type "Create Group" which is automatically get flagged on creation by Using hook\_node\_presave().

Now flagged nodes(Groups) are also showing in wishlist then i have added draggable views into the existing wishlist view for grouping content by drag and drop by changing order.

But after changing order ,the changed order is not shaving into database,i think its a module issue which is not compactible with views relation.

Is there any alternative like is it possible to add custom select list in group content type which will show list of flagged node per user .

# Answer
You can group existing flagged content into smaller groups through the Content type Group you created with the help of Views display type `Entity reference`.

1. Create Content Views listing nodes that user might flag, don't create Page nor Block display, then when you save the View add the Display `Entity reference` from the `Add` dropdown.
2. Under `Format: Entity Reference list` Settings choose **Content: Title** as the Search field

In the results you should now see a list of node titles that can be flagged.
3. Add a new Relationship **Content flag** from the `Flag` category and configure it:
Tick **Include only flagged content**
Flag **Bookmark** (or whatever the name of your flag is)
By **Current user**

This will now filter out only the nodes that are already flagged by the current user. You are probably logged in as admin so you will now only see nodes that admin has bookmarked.
4. Adjust other views settings (Pager for example to show all items), `No results behavior` to **You haven't bookmarked any content yet** and save the View.
5. Edit your Group content type and add a new **Reference** field that references unlimited number of Content (nodes).

You'll probably want to make it a **Required field**

Under `Reference type` **Reference method** choose the Views you created in the first step. You will only see views displays of Entity reference type here.

A new option will appear `View used to select the entities`. Choose your exact views display here.

There are no arguments to pass, leave that empty (it is done through the flag relationship).
6. On the `Manage form display` settings for that field choose **Check boxes/radio buttons**.

Now when your users go to create a new Group node, they will be able to choose from a list of nodes they had already flagged:

In case you need your users to control the order in which the selected nodes appear in the Group you can change the field widget to `Autocomplete`, that way the choices can be reordered:

but this way the users have to search for node titles. You can help them by duplicating the views into a Block display and displaying it only on Create/Edit Group pages so users can see which title to search for.
> 1 votes

# Answer
Other way to do the same by using custom module (hook\_form\_alter).

```
function nestle_viewalter_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

$entity_id='recipe';

$x = db_query("SELECT title FROM {node_field_data} AS nfd WHERE nfd.type = :nid", array(':nid'=> $entity_id))->fetchAll();

if($form_id == "node_recipe_edit_form" ){
$node = $form_state->getFormObject()->getEntity();
$nid = $node->id();
$value_whishlist = db_select('custom_whislist', 'cw')
             ->fields('cw', ['whislist'])
             ->condition('node_id', $nid)
             ->execute()->fetchCol();

             }
foreach ($x as $s)
{

$v[$s->title]=$s->title;

}

if($form_id == "node_recipe_form" || $form_id == "node_recipe_edit_form" )
{
    $form['whislist'] =[

    '#type' =>'select',
    '#title' =>t('Choose whislist item'),
    '#options' =>$v,
    '#multiple' => true,
    '#default_value' =>!empty($value_whishlist) ? $value_whishlist : '',
    ];

foreach (array_keys($form['actions']) as $action) {
if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
  $form['actions'][$action]['#submit'][] = 'nestle_viewalter_form_submit';
}
}
 }
 }
 function nestle_viewalter_form_submit(array $form, FormStateInterface $form_state){
$node = $form_state->getFormObject()->getEntity();
$nid = $node->id();
$path = \Drupal::request()->getpathInfo();
$arg  = explode('/',$path);
if ($arg[3] == 'edit'){
    $delete = db_delete('custom_whislist')
    ->condition('node_id', $nid)
    ->execute();

}

foreach($form_state->getValue('whislist') as $val){
        $query = db_insert('custom_whislist')
        ->fields([
        'whislist'=>$val,
        'node_id'=> $nid
        ])
        ->execute();
        }

($arg[3] == 'edit') ? $form_state->setRedirectUrl(new Url('entity.node.canonical', array('node' => $nid))) : '';
 }

```
> 0 votes

---
Tags: views, 8
---


# Question
Title: How to change upload destination from public to private when there are uploaded files in database?
There are a few fields that uses public upload destination. I changed it globally right now, as far as I know it uses private upload destination from now. But how can I change previously uploaded files' upload destination (programmatically)?

# Answer
> 0 votes
```
$dest = 'private://';
$file = file_move($file, $dest)

```

Change individual file from public to private and vice-versa

---
Tags: 8, files
---


# Question
Title: How do I add a CSS class to a p tag in CKEditor?
The standard center button only applies a in-line style to the HTML. But how can I add a class 'text-center' to a paragraph or selection by clicking the following icon? I went ahead and created a custom button on CkEditor.

```
(function($) {
CKEDITOR.plugins.add( 'center', {
    icons: 'center',
    init: function( editor ) {
        editor.addCommand( 'center', genCommand());
        editor.ui.addButton( 'center', {
            label: 'Align text on center',
            command: 'center',
            toolbar: 'center'

        });
        if ( editor.contextMenu ) {
            editor.addMenuGroup( 'centerGroup' );
            editor.addMenuItem( 'centerItem', {
                label: 'Change link',
                icon: this.path + 'icons/center.png',
                command: 'center',
                group: 'centerGroup'
            });
            editor.contextMenu.addListener( function( element ) {
                if ( element.getAscendant( 'center', true ) ) {
                    return { abbrItem: CKEDITOR.TRISTATE_OFF };
                }
            });
        }
        CKEDITOR.dialog.add( 'centerDialog', this.path + 'dialogs/center.js' );
    }
});
function genCommand( name ) {
    return {
            exec: function( editor ) {
                editor.insertHtml('<p class="text-center>' + editor.getSelection().getNative() + '</p>');
            },
    };
}
})(jQuery);

```

What it is doing is nothing. In the case there is a selection, it deletes the selection and markup.

What I need:

1. If there is a line saying "text", I need `<p class="text-center">text</p>`
2. In the case there is a selection, make 1 out of the selection

# Answer
Using WYSIWYG/CKEditor in Drupal, you can add classes in the UI and they will show up in the Style drop down.

In the CSS tab of the WYSIWYG Profile you are editing:

You need to have the "Font style" plugin checked off in the config.

Now any element you add here can have it applied, so you would add:

`Center P Tag=p.text-center`

line to this config.

Then, add some text in the editor, and highlight the text (CKEditor should automatically wrap regular text with a `p` tag). You should then see the option in the drop down as "Center P Text". You will *only* see these options available when you've highlighted elements that are applicable. It will then apply the class to the highlighted element, the `p` tag.

I use this all the time to add classes to various elements just as you are trying to do.
> 0 votes

---
Tags: 7, wysiwyg
---


# Question
Title: How to sync configuration between multiple developers' environments
D8 Configuration management is really awesome and easy to use when there's only one developer working on a project. We are running into challenges in keeping configuration synced between environments when more than one developer is introduced to a project at the same time.

Example:

* Developer A is working on feature A. Exports configuration to their feature branch and pushes it to a shared develop branch.
* At the same time, developer B is working on feature B and does the same thing - pushes feature configuration to the shared develop branch.

How do you import feature A and feature B concurrently?

# Answer
> 3 votes
Don't push to the develop branch directly. You should have a branch and merge strategy. If using GitHub or GitLab or similar, you would do a pull request of *your* branch to develop.

A common strategy (or one of) is the Git Flow workflow. Some links to explain Git Flow:

There are a handful of strategies, use whatever will fit for your team.

One of the few circumstances I ran into with merge conflicts was if someone was working on something touching the same configuration areas as another person.. we avoided this by just coordinating the work well.

---
Tags: configuration
---


title: Webform Validation Allow Lowercase Only

text:
# Question
Title: Webform Validation Allow Lowercase Only
I have an email field in a webform that will trigger a rule that checks against that field against a user's email. The issue is, rules is case sensitive so if the webform field had capitals, and the user's email does not, they don't match like they should.

In webform validation, there are two options that should work for me to force the email to only contain lowercase values.

Regular expression, case-sensitive Validates user-entered text against a case-sensitive regular expression. Works with: email, hidden, number, textarea, textfield. Regular expression, case-insensitive Validates user-entered text against a case-insensitive regular expression. Works with: email, hidden, number, textarea, textfield.

Which one of these should I use, and what is the regular expression so that it only disallows capital letters?

Thanks!

# Answer
> 0 votes
Figured it out - Regular Expression, case-sensitive:

Regex Code: \[A-Z\]

Negate Rule is checked.

---
Tags: forms, rules, webforms
---


# Question
Title: How to programmatically get the Title for a Local Menu Task?
I have a long list of menu items so i'll cut it short here:

```
$items['admin/skyview'] = array(
    'title' => 'Skyview Main Page',
    'type' => MENU_NORMAL_ITEM,
    'access callback' => TRUE,
    'page callback' => 'skyview_main_page',
);
$items['admin/skyview/tab1'] = array(
    'title' => 'Skyview',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'access callback' => TRUE,
    'weight' => 0,
);
$items['admin/skyview/tab5'] = array(
    'title' => 'Sites',
    'type' => MENU_LOCAL_TASK,
    'access callback' => TRUE,
    'weight' => 4,
    'page callback' => 'skyview_sites',
);

```

But my question is how do I programmatically get the title of 'Sites' for tab5? When I use `menu_get_active_title` it returns '`Skyview Main Page`' instead.

I've looked through phpstorm for what options it gives me, but I really don't find anything to get the title of a menu local task, however I noticed this can be done in D8 but can it be done in D7?

# Answer
> 1 votes
I figured out how to finally get the title.

I was using `dpm(menu_get_item());` which listed an array, but I had no idea how to access it. I just had to turn it into a variable to hold that data, then I could access it!

```
$db_site = menu_get_item();
$db_site = $db_site['title'];

```

---
Tags: 7
---


# Question
Title: How can i use MATCH and AGAINST with db_select?
I have a query like:

```
$query = db_query("
    SELECT *, MATCH(field1,field2) AGAINST ('$s' IN BOOLEAN MODE) AS Relevance
    FROM {my_table}
    ORDER BY Relevance DESC, created DESC
    ");

```

That is working well with db\_query.
How can i use same query with db\_select function for drupal 7?

# Answer
> 3 votes
Adding an expression should work:

```
 $query = db_select('foo');
 ...
 $expression = 'MATCH(field1,field2) AGAINST (:search IN BOOLEAN MODE)';
 $query->addExpression($expression, 'Relevance', [':search' => '$s']);
 ...

```

See `SelectQuery::addExpression` for more info.

---
Tags: 7, database
---


# Question
Title: How to add block-like visibility settings to nodes?
I have created a custom content type 'campaign' in my module using `hook_node_info()` and added fields using `hook_field_group_info()`. This campaign content type will be shown to users site wide in modals/pop-ups using CTool modal on page load (`hook_init()`).

What I'm looking for is, to give an option to admins to restrict this pop-up/modal for different roles or paths. Same like block section is doing. For example whether to show a block on `node/104` or not, or wether to show a block for (anonymous) users only or not. Like shown in the screenshot below.

My aim is that, while creating 'campaign' nodes, admins should be able to select pages or roles to show that particular campaign or not.

Can you please guide me how can I use Drupal block logic here? Or do you maybe can make some code suggestions I can start with in my custom module?

# Answer
Block visibility rules are kind of fundamentally different from nodes in that nodes are intended to always show up using the "full" or "default" display mode in the main content block/region of the specific node's unique URL. On the other hand, blocks go hand-in-hand with the ability to be placed in any region on any page. Block visibility can group permissions (ie role based rules) along with path-or-url-based rules, but nodes cannot natively do this.

I can think of three possible alternatives (there might be more):

1) Embed Nodes in a block using one of these modules, and then use block visibility rules to place it. This has the drawback that you have to tie things together quite manually in two places.

2) If you're showing campaign nodes on other nodes, then you can use an entity\_reference field to reference the campaign node from another node (or vice versa) and then just set the entity reference field's display settings to render the entity as if it were a field on the node.

3) Write a completely custom solution to mimic block visibility rules for nodes. I'd start with a Text (long) field (call it field\_campaign\_urls), then in a node\_form\_alter() hook alter the display to show up in a vertical tab (or you could use Field Group module to do this in the UI). Then you'd need to implement a hook that gets called on all pages, e.g. hook\_page\_alter test the internal Drupal URL (and optionally also the pathauto alias) for a match against all values in the field\_campaign\_urls database table. The challenge here will be writing the wildcard functionality, you'll need to figure out how to convert `some/url/*` into a database condition `LIKE 'some/url/%'` This is also where you might want to start digging into the block.module code to find out more about the internal structure of how block visibility query logic works. Finally, you'll need to combine this logic with your custom node access logic as well. And indeed figure out which block region you want to add your node to. You may leverage drupal\_add\_region\_content to add your rendered node to a specific region.
> 1 votes

# Answer
You probably are overthinking this.

Simply add two new fields to your campaign content type, one multi-value node reference field where editors select the pages, and one multi value select (list) field with your role names as options. That's all you need to control the visibility of your modal.

Then have a custom block, which gets the current node ID it's displayed on and the current user role and do some checks through all your campaigns (maybe via some database query) to get the ones where these values match and then load and display the matching campaigns.

Done.
> 0 votes

# Answer
For any content which is created by custom/added from drupal admin UI, Access control can be enabled from Content Access module.
> -1 votes

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


# Question
Title: How to change the "firstDay" option of the datepicker JQuery UI element in the UI of webforms?
Where can I change the firstDay option of the datepicker in the UI of webforms? Can it only be done by writing some code?

# Answer
> 0 votes
You can set the date picker 'First day of week' via 'Regional settings' (/admin/config/regional/settings)

---
Tags: webforms
---


# Question
Title: How do I perform a redirect to the cart?
I'm trying to redirect the user to the cart from a custom page using the following code.

```
return new RedirectResponse(\Drupal::url('cart'));

```

Is there a function to go directly to the cartrce? If not, what is the route name for the cart page?

# Answer
> 1 votes
If you use the Devel module, you could also find the right routes on "/devel/routes".

An then do something like:

```
  $url = Url::fromRoute('commerce_cart.page');

  //$url->toString();
  $form_state->setRedirectUrl($url);

```

# Answer
> 1 votes
Since the question is saying *custom page*, I take the redirect is not done on a form. If the controller handling the page extends the `ControllerBase` class, the code to redirect users to the cart page is similar to the following one.

```
// Put the following line at the top of the file containing the controller class.
use Drupal\Core\Controller\ControllerBase;

// This is the controller method that handles the custom page.
public function redirectToCart() {
  $this->redirect('commerce_cart.page');
}

```

There isn't any need to conver the route name in a URL object: `UrlGeneratorTrait::redirect()` (from the `UrlGeneratorTrait` trait used from the `ControllerBase` class) accepts the route name as first argument.

Redirecting from a form require different code. Supposing the form class extends the `FormBase` class, you would use the following code.

```
// Put the following lines at the top of the file containing the form class.
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

//This is the form method that handles the form submission.
public function submitForm(array &$form, FormStateInterface $form_state) {
  $form_state->setRedirect('commerce_cart.page');
}

```

If the route requires parameters, `UrlGeneratorTrait::redirect()` and `FormState::setRedirect()` accept them as second parameter (an array).

The route name for the cart page is shown on the first line of modules/cart/commerce\_cart.routing.yml.

```
commerce_cart.page:
  path: '/cart'
  defaults:
    _controller: '\Drupal\commerce_cart\Controller\CartController::cartPage'
    _title: 'Shopping cart'
  requirements:
    _access: 'TRUE'

```

# Answer
> 0 votes
you can use Symfony Component for redirect

```
  $url = "/cart";
  $response = new Symfony\Component\HttpFoundation\RedirectResponse($url);
  $response->send();

```

If you want route name you will get with following code

```
$url_object = \Drupal::service('path.validator')->getUrlIfValid('/cart');
kint($url_object->getRouteName());

```

---
Tags: commerce
---


# Question
Title: Is it possible to add template suggestions for image styles?
I am experimenting with durpal 8 theme hook suggestions. I tried to customize the the theme suggestions based on the style name. I want the ability to add a twig template for each style if I wanted so I tried this:

```
function themename_theme_suggestions_image_style_alter(&$suggestions, array $variables, $hook) {
  $suggestions[] = [$hook . '__' . $variables['style_name']];
}

```

and

```
function themename_theme_suggestions_image_alter(&$suggestions, array $variables, $hook) {
  $suggestions[] = [$hook . '__' . $variables['style_name']];
}

```

I was expecting to see this as a theme hook suggestion in the html comments printed by in the page source after enabling twig debuging.

Using xdebug the hook is triggered but I don't find it in the suggestions list in the html after enabling twig.config.debug to true.

am I missing anything?

# Answer
1. `hook_theme_suggestions_HOOK_alter` doesn't use a third argument.
2. You are supposed to add the suggestions as string.

---

```
/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYTHEME_theme_suggestions_image_style_alter(array &$suggestions, array $variables) {
  $suggestions[] = $variables['theme_hook_original'] . '__' . $variables['style_name'];
}

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYTHEME_theme_suggestions_image_alter(array &$suggestions, array $variables) {
  $suggestions[] = $variables['theme_hook_original'] . '__' . $variables['style_name'];
}

```
> 2 votes

---
Tags: 8, theming, media
---


# Question
Title: Sending an email to everyone with a certain role
Me: Small business owner with no coding or Drupal background who wants to learn by doing instead of hiring a developer for every small thing.

Goal: I have a Drupal 7 website and would like to send different types of emails to users of specific roles using the Rules (or an easier way if you care to suggest it). I've explored using Rules to accomplish this with some success by cloning similar ones and making small changes, but making one from scratch is more challenging. I've wrapped my head around scheduling the event and creating the email in the action, but specifically editing the condition is a barrier. I assume that the element "User has role(s)" is what I should use, but I'm confused on how to drill down the "data selector" under the USER area. I'd like the system to evaluate all members of the site and email everyone with a specific role...I don't see an appropriate option. Maybe I'm looking at the wrong condition element. Little lost - I'm sure it is a painfully obvious to someone who knows what they're doing.

All constructive suggestions and guidance welcome on how to accomplish this - trying to learn!

# Answer
If all you want to do is send emails to users of a certain role, you can use the Mass Contact module. It enables a user to send an email to users by role or taxonomy. It is very easy to use, without any coding knowledge necessary. I have used it on a couple of business-related sites.

The other alternative is to use Simplenews. This is used mostly for sending email newsletters to lists of subscribers, if that is the kind of email you want to send.

But if you really want to use rules, I suggest you go through some documentation like this. Under the "Add a new action" of your rule, under the "System" section, there is a "Send email to all users of a role" action. That may be what you need.
> 1 votes

---
Tags: users, emails
---


# Question
Title: How to add warning message before module is uninstalled
The module in question has a content entity, entity1, that has another content entity, entity2, that depends on entity1. I would like to add a warning before uninstall of the module if there are currently entity2's that exist and that depend on entity1. The warning will suggest to delete the entity2 and then entity1 before the module can be uninstalled. How could I do this?

# Answer
Before a module is uninstalled, Drupal invokes all the services implementing `UninstallValidatorInterface` and tagged with *module\_install.uninstall\_validator*. Their `validate()` method (see `BookUninstallValidator::validate()`, for example) returns an array of strings explaining why the module cannot be uninstalled, which are then shown in the user interface.

Notice that the `validate()` method receives the name of the module as parameter. While normally the module implementing the `UninstallValidatorInterface` service checks if itself can be uninstalled, a `UninstallValidatorInterface` service can avoid any module is uninstalled.

In Drupal 7, there isn't anything similar. The only way to achieve this is altering the page showing the list of the installed modules to show a message near a module.
> 1 votes

---
Tags: entities, installation
---


# Question
Title: Why are media files used in zero places not deleted?
Unused media files (.jpeg .mp4 etc.) are remaining permanently even though unused.

This is shown in the `/admin/content/files` page in our Drupal 8.6.3 system.

It could be that, at migration from Drupal 7, we weren't careful enough.

Is there any way I can force the deletion of these files using Drupal functionality?

I haven't seen any fully ready a Drupal 8 module to remedy this seemingly common situation.

# Answer
I've come across this before with webform submission files and the site getting confused about the path.

If you actually try and view 1 of the files in the list does it exist? As you may find it doesn't exist but drupal has kept a record of the file in the database. When drupal tries to do is file tidy up on cron run it's erroring because the file its trying to delete doesn't exist (But its not then smart enough to delete the row out of the database)

The safest solution would be to manually recreate these files in the position /admin/content/files thinks it should exist and then rerun the cron and it should delete your test file and the row in the database
> 0 votes

---
Tags: media
---


# Question
Title: How can I populate multiple blocks on a paginated page?
my problem seemed simple to solve and how to do it. But the paging did not work properly ..

As we see in the images, we have:

* Main block with an image and description. It only shows 1 element.
* Sequential block, an image and a description that the second content must show. It only shows 1 element. It is a block that is attached to the first
* Third block with image and description showing the third content. It only shows 1 element. It is a block that is attached to the first
* And at the end of a list of 3 cards, showing image and description. It must be shown from the third image onwards. It is a block that is attached to the first

It is content similar to news, the idea is to show different types of blocks for each content. And then paginate all the contents. The problem I found is that when you attach elements or when doing so with blocks you can only page one block. For example, when paging the main block, I will paginate all the attached blocks of an element. On the other hand, if I use the block of 3 cards, and I paginate it for this, I will paginate all the attached blocks with three elements.

The idea of mockups, would paginate the whole set with its corresponding content. That is, for the first page I have 6 elements shown in different ways, for the second page should show 6 to 12, the third 6 to 18. And to be more specific the main block will have the content 1 of page 1, the element 7 on page 2, and item 13 on page 3 and so on.

Example complete:

I hope you understand

# Answer
I think building this functionality using custom code would be the way to go as views isn't really capable of this sort of thing.

If it was me I'd make a custom block to replicate this giving you alot more control.

But if you really want to use views you could maybe just have the 1 block and make it show 11 item per page. Then create a views template for the view and add some bits in there e.g. if you're using unformatted list you could copy views-view-unformatted.html.twig and save as views-view-unformatted--VIEWNAME--block-1.html.twig and then do something like:

```
{% for row in rows %}
  {%
    set row_classes = [
      default_row_class ? 'views-row',
    ]
  %}
  <div{{ row.attributes.addClass(row_classes) }}>

    {% if loop.index == 1 %}
     //use elements from $row to build display 1
    {% endif %}

    {% if loop.index == 2 %}
      //use elements from $row to build display 2
    {% endif %}
    ....
    ....
  </div>
{% endfor %}

```

Downsides of this you can't easily use different image styles or amount of text per row without using some contrib modules and other bits (I haven't actually attempted this but know there are modules to let you do more in twig, as mentioned custom block would be better though)
> 2 votes

---
Tags: views, 8, paging
---


title: How to get image path in view?

text:
# Question
Title: How to get image path in view?
I have created a content type having two fields:

1. Title
2. Image (multiple image field)

Then I create a page view for the same. Added these two fields. Now I have to create an external theming in view so from view-Theme Information- Row Style output, I have created a `view-tpl.php` page in the templates folder.

I have given this design in this view:

```
<style type="text/css">
    .imgStyle
    {
        width:100px;
        height:100px;
        border:3px solid grey;
    }
</style>

<img id="mainImage""
     src="images/collection-img/nandikesvara-front-3000-06.png" height="500px" width="540x"/>
<br />
<div id="divId" onclick="changeImageOnClick(event)">
    <img class="imgStyle" src="images/collection-img/nandikesvara-front-3000-06.png" />
    <img class="imgStyle" src="images/collection-img/nandikesvara-back-3000-06.png" />
    <img class="imgStyle" src="images/collection-img/nandikesvara-front-3000-06.png" />
    <img class="imgStyle" src="images/collection-img/nandikesvara-back-3000-06.png" />
    <img class="imgStyle" src="images/collection-img/nandikesvara-front-3000-06.png" />
</div>
<script type="text/javascript">

    var images = document.getElementById("divId")
                         .getElementsByTagName("img");

    for (var i = 0; i < images.length; i++)
    {
        images[i].onmouseover = function ()
        {
            this.style.cursor = 'hand';
            this.style.borderColor = 'red';
        }
        images[i].onmouseout = function ()
        {
            this.style.cursor = 'pointer';
            this.style.borderColor = 'grey';
        }
    }
    function changeImageOnClick(event)
    {
        event = event || window.event;
        var targetElement = event.target || event.srcElement;

        if (targetElement.tagName == "IMG")
        {
            mainImage.src = targetElement.getAttribute("src");
        }
    }
</script>

```

So I want to fetch one by one image path to pass in src of images. I have tried this `$fields['image']->content` but it print images as an object. How can I get the paths of images to pass in `src` tag.

# Answer
Here's a Drupal 7 example showing how to use:

`field_get_items()` to select the field from the node,

`file_load()` to load the image file,

`image_load()` to get the URI from the image file

`image_style_url()` to format the image differently for different contexts

... and as a bonus, check for good data and substitute a default image if the field image is no good.

```
// If there is a field image.
if (!empty($node->field_image)) {
  $field = field_get_items('node', $node, 'field_image');
  if (!empty($field[0]['fid'])) {
    $image_file = file_load($field[0]['fid']);
    $image      = image_load($image_file->uri);
  }
}
// If image, then scale it. If not use the default image.
if (!empty($image)) {
  if (is_string($image)) {
    $image_source = $image;
  }
  else {
    $image_source = $image->source;
  }
  $url        = image_style_url('image_style', $image_source);
  $url_mobile = image_style_url('image_style_mobile', $image_source);
}
else {
  $url        = 'https://example.com/sites/default/files/default_image.png';
  $url_mobile = 'https://example.com/sites/default/files/default_image_mobile.png';
}

```

Hope this helps. Good luck!

**EDIT:** @Kevin makes a very good point in the comments above:

> All of this complexity can be avoided by using entity view modes and not doing field based views.

Basically, Drupal gives you the ability to set up view modes in the "Manage Display" tab for each content type. There, you can decide which fields will be shown or hidden in each view mode, and how they should be formatted for display. If you use this feature, you shouldn't need to deal with it in PHP template files.
> 1 votes

# Answer
You get the URI of an image (and file) field by:

```
$node->field_image->entity->getFileUri();

```

And you get the url of a styled instance of your image by:

```
$bildstyler = ImageStyle::load('thumb');
$bildstyler->buildUrl($node->field_image->entity->getFileUri());

```
> 0 votes

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


title: Per bundle storage?

text:
# Question
Title: Per bundle storage?
In Drupal 7 there was the start of Per-Bundle Storage (PBS) to try to store field data in a single database table if that made sense and was possible given the nature of the field. The PBS for Drupal 7 module didn't ever become very popular, though and was not ported to Drupal 8.

I understand it's possible to write custom Entity code for Drupal 8 to store data in a single table if you want (e.g. the `User` entity stores it's fields in users\_field\_data).

I'm curious if there's an easy solution I've overlooked to store several fields in a single database table.

# Answer
Answering my own question based on comments here and my own experimentation. In Drupal 8 the creation of an entity with base fields is simpler than it was in Drupal 7. Here are the steps I followed to create an entity in Drupal 8 with fields in the single table. I'll talk about my situation: a Dog entity.

1. There's some good general docs on Drupal.org about entities and fields in Drupal 8. This page about defining and using content entity field definitions is particularly useful.
2. I also read this skvare article about Entities in Drupal 8 which has a lot of great advice.
3. I started by installing Drush.
4. I ran `drush generate module-content-entity` and answered the questions. I answered the questions:
    * "yes" to making it fieldable
    * "no" to bundles for my case.
    * The rest of the answers seemed straightforward.
5. In the `exampledog/src/Entity/Dog.php` file I modified the `baseFieldDefinitions` function to return an additional field. Some examples and documention on field types are in the drupal.org doc page mentioned earlier.

That's it. Revisions seem to work well for these fields. Views integration works well for these fields. The fields are all stored in the base table.
> 5 votes

---
Tags: 8, entities, database
---


# Question
Title: AJAX callback issue when using 'Manage Form Display' and 'Manage Display'
Good day everyone,

So I have an issue that I haven't been able to google. The issue seems rather simple but I don't know what's causing it. When i'm managing field displays in either the form or a view, the ajax 'throbber' icon pops up and the ajax request is never completed. It will continue to show the throbber indefinitely. If I drag the field to another location, it will create another instance of the throbber icon and no ajax request is ever completed. I can do this any amount of times. When I save the form and a field is in the AJAX state, it just reverts back to whatever it was originally. The weird thing is, if I press the cog to change the settings of the field and that field was in the 'perpetual ajax request' state, it will then complete the ajax request as expected.

This leads me to believe that dragging and dropping the fields (and changing the formatter/widget) aren't actually sending any ajax requests. This is also confirmed by checking the Network tab in Chrome's tools. Nothing is sent when dragging fields but when pressing the cog "teaser?ajax\_form=1&\_wrapper\_format=drupal\_ajax" request is sent.

I'm at a loss as to what is happening. It only started recently (last couple hours of development) and I went through the changes I've made in that time to try and identify the problem and have come up with nothing. I checked for differences from the production site and nothing... I'm not sure what to do next. Has anyone experienced this problem and successfully fixed it?

# Answer
> 1 votes
Well, I feel like a fool as the answer was actually simple... I had forgotten about switching all input elements to actual button elements. This broke any AJAX request only when the type was a submit button.

---
Tags: 8, ajax
---


# Question
Title: How can I get the current node view mode and add to block template suggestion?
In my code, I need to get the current view mode of the node to be able to pass it to be used as a block template suggestion.

The function I have set up is able to grab all available view modes, but I just want the current one. Possibly a condition that I haven't come across yet would do the trick?

```
function mytheme_theme_suggestions_block_alter(array &$suggestions, array $variables) {
// Add template suggestions based on the current view mode and node type.
  if ($node = \Drupal::routeMatch()->getParameter('node')) {

   $view_modes = Drupal::entityQuery('entity_view_mode')
   ->condition('targetEntityType', 'node')
   ->execute();

   foreach ($view_modes as $view_mode) {
   $view_mode = str_replace('node.', '', $view_mode);
   $suggestions[] = 'block--' . $node->getType() .'-'. $view_mode;
  }
 }
}

```

# Answer
You say in your comment it is not useful for you and I doubt there are many use cases for this at all, because normally as main content a node is rendered in the full view mode.

Nonetheless trying to answer: A block is built based on contexts and at the moment this is the route, which you have to add as cache metadata to the block. You can then base the decision which view mode the node uses on this route by checking `_entity_view` of the route definition. If the view mode is controlled by code somewhere else you need to pull this in as context as well.
> 0 votes

---
Tags: 8, blocks, hooks
---


# Question
Title: Grant permission for custom role from hook_install programmatically
Drupal Version: 8.5.5

Need to assign permission to existing role during module installation: Am using below code in hook\_install:

```
use Drupal\user\RoleInterface;
use Drupal\user\UserInterface;
function hook_install() {

 $permission = 'test permission';
    $tester_rid = RoleInterface::TESTER;

    if ('tester' == Role::load($tester_rid)) {
      $tester_role->grantPermission($permission);
      $tester_role->save();
    }
}

```

Above grant permission is not working. I have also tried with

```
user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, array(
      'my custom permission',
    ));
user_role_grant_permissions(RoleInterface::TESTER, array(
      'my custom permission',
    ));

```

Above hook\_install is not working.

Pls help

# Answer
> 9 votes
Try this:

```
use Drupal\user\Entity\Role;

function mymodule_install() {
  $role_object = Role::load('my custom role name');
  $role_object->grantPermission('my custom permission name');
  $role_object->save();
}

```

---
Tags: 8, users, hooks, installation
---


# Question
Title: View date filter using years as an offset
Is there a way to use years as a date filter offset? What I want is to set it so that it it loads all content from the start of the previous year. So \>= 01-01-2017 this year, \>= 01-01-2018 next year, etc. Is there a way to do that in the View configuration so that it's dynamic? I'm sure I could do it with custom code by altering the query, but I'd rather avoid that.

# Answer
> 2 votes
It turns out this was more of a PHP strtotime() question. I just had to figure out the appropriate phrase to get the time frame I wanted, which is: "first day of january last year". I placed that phrase in the filter's offset value.

---
Tags: views, 8, datetime
---


# Question
Title: Drush rsync and drupal composer wrong destination dir
I'm trying to sync two D8 sites. Both set up with drupal composer which means that the directory structure is a bit different than usual. Composer puts drupal files inside `web` sub directory like this:

```
/var/www/drupal8
|-- composer.json
|-- composer.lock
|-- drush
|-- scripts
|-- vendor
`-- web
    |-- autoload.php
    |-- core
    |-- index.php
    |-- modules
    |-- profiles
    |-- robots.txt
    |-- sites
    |-- themes
    |-- update.php
    `-- web.config

```

My aliases file looks like this:

```
<?php

$aliases["local"] = array (
  'root' => '/var/www/drupal8/web/',
  'uri' => 'http://local.site',
);

$aliases["remote"] = array (
  'root' => '/var/www/drupal8/web/',
  'uri' => 'http://site.example.com',
  'remote-user' => 'dev',
  'remote-host' => 'site.example.com',
);

```

When I do `drush rsync @remote @local` I end up with all files from `@remote/web` inside `@local/web/web` like this:

```
/var/www/drupal8
|-- composer.json
|-- composer.lock
|-- drush
|-- scripts
|-- vendor
`-- web
    |-- autoload.php
    |-- core
    |-- index.php
    |-- modules
    |-- profiles
    |-- robots.txt
    |-- sites
    |-- themes
    |-- update.php
    |-- web
        |-- autoload.php
        |-- core
        |-- index.php
        |-- modules
        |-- profiles
        |-- robots.txt
        |-- sites
        |-- themes
        |-- update.php
        `-- web.config
    `-- web.config

```

I can't edit aliases to remove `web` sub dir from `root` path because then drush will not work as it will complain that it *needs a higher bootstrap level to run* (because it won't know where is drupal root folder).

How can I instruct drush to use proper destination path for synchronisation?

# Answer
I had the same problem took me ages to find out what was wrong. Turned out to be the slash (/) behind the root folder that was missing.

```
self.site.yml

remote:
  host: domain.com
  user: user
  root: /home/user/public_html/
  uri: http://domain.com

```

@see https://unix.stackexchange.com/questions/402555/why-add-a-trailing-slash-after-an-rsync-destination

Turned out to be a bug in drush https://github.com/drush-ops/drush/pull/3405
> 1 votes

# Answer
I cannot reproduce this problem. What version of Drush are you using? What version of rsync, on what OS?

I created temporary aliases for two sites, and set their root directory to /tmp/a and /tmp/b, respectively. I just put a couple of test files in /tmp/a.

```
$ tree /tmp/a
/tmp/a
├── composer.json
└── web
    └── index.php

1 directory, 2 files
$ drush rsync @tmp.a @tmp.b
You will delete files in /tmp/b/web/ and replace with data from /tmp/a/web//
Do you really want to continue? (y/n): y
$ tree /tmp/b
/tmp/b
└── web
    └── index.php

1 directory, 1 file

```

This behaves as expected.

I also did another test, using a remote alias as the source, and received similar results.

If you would like to see exactly what parameters Drush is using to call rsync, add the `-s` flag to the command line:

```
drush -s rsync @remote @local

```
> 0 votes

---
Tags: 8, drush, composer
---


title: Remove height of empty fields in Views

text:
# Question
Title: Remove height of empty fields in Views
I have setup some Structure/Views for items that I am pushing to the front page. I have 2 separate link items (1 displays facebook icon, 1 displays arrow icon) some instances will have both links, some instances will have 1, currently if I leave the facebook link field blank, the display still leaves the space for that item.

It seems related to the font awesome "fas" class that needs to be added to the Views setting in order to load the icons (icons are used in "content:" in css). Once I remove the "fas" class the height of the empty link field removes itself from the page. How do I retain "fas" class on the: View (structures/views/ (item) / link field; but remove the height of empty fields?

code:

```
<div class="views-field views-field-field-link-special">
<div class="field-content readmore fas">
<a href="/jjweb/web/node/24" target="_blank">Read More</a> </div></div>
<div class="views-field views-field-field-link-facebook">
<div class="field-content readfacebook fas"> </div></div>

```

The below screenshot shows how the class is applied to the View/Field, with "Hide if Empty" applied.

# Answer
> 0 votes
The cleanest solution would be to hide a field that has no content.

Go into the configuration of each field you output on the view and under **No results behaviour** check **hide if empty**

---
Tags: views
---


# Question
Title: How to get the revisions list of a node and delete them all?
Revisions and how to delete them all. For Drupal 7, there’re plenty of modules that do that or even limit the revisions that are kept or even delete everything that is older then x-days, but not for Drupal 8.

It seems there is nothing out there. Searching through the database is something I like not to do.

Any ideas?

# Answer
> 11 votes
Yes, as you says there is a list of modules that can do this in Drupal 7 like:

Node Revision Delete

> The Node Revision Delete module lets you to track and prune old revisions of content types. Define the max amount of revisions to keep per content type. Run on Drush, cron run or on a different period (daily, weekly, etc).

Node Revision Restrict

> The Node Revision Restrict module allows you to restrict revisions of node for each content type. This module has an admin interface to specify node revision threshold for each content type available. The possible setting include node type with corresponding revision limit, provided on the Node Revision Restrict configuration form. Note that this module does not and cannot delete the current revisions of a node.

Node Revision Cleanup

> Node Revision Cleanup is designed for really big databases. And site administrators who are comfortable with Drush. The concept behind this module is to be able to run multiple invocations at the same time, via Drush to maximize the number of node revision deletions per second.

Revision Deletion

> This modules enables the ability to mass delete aging node revisions. Possible settings include node type, the age of node revision before being deleted, along with a Cron frequency setting. The revisions may be deleted after review on an administer page as well. This module will NEVER delete the current revision of a node, nor will it allow you to do so.

**And for Drupal 8**, well at this moment there is not module for do that, but you can use:

To get the revision list of a node:

```
$vids = \Drupal::entityManager()->getStorage('node')->revisionIds($node);

```

See Nodes now have a storage controller; node\_revision\_list() removed.

To delete a revision revision you can use the node\_revision\_delete() function, but at the end see the function code:

```
function node_revision_delete($revision_id) {
  \Drupal::entityTypeManager()->getStorage('node')->deleteRevision($revision_id);
}

```

So, is better if you just use:

`\Drupal::entityTypeManager()->getStorage('node')->deleteRevision($revision_id);`

# Answer
> 6 votes
The suggestions in here are correct, though a few things is worth mention.

```
$vids = \Drupal::entityManager()->getStorage('node')->revisionIds(node_load($nid));

```

But since this is marked as deprecated, it should be replaced by:

```
$vids = \Drupal::entityTypeManager()->getStorage('node')->revisionIds($node);

```

The example code in here also try delete the default revision and that will cause `[error] Default revision can not be deleted`. To avoid that I suggest that you wrap the removal in something like:

```
  // If revision id is not default, remove it.
  if ($vid !== $node->getLoadedRevisionId()) {
    print 'Removing revision ' . $vid . PHP_EOL;
    \Drupal::entityTypeManager()->getStorage('node')->deleteRevision($vid);
  }

```

# Answer
> 4 votes
Snippet to delete all but the latest revision of a specific node:

```
<?php
  try {
    $nid = 123; // Your node id
    $vids = \Drupal::entityManager()->getStorage('node')->revisionIds(node_load($nid));
    foreach($vids as $vid){
      \Drupal::entityTypeManager()->getStorage('node')->deleteRevision($vid);
    }
  } catch (Exception $e) {
    // Latest revision will not be deleted but throws an error
    return $e->getMessage();
  }
?>

```

# Answer
> 3 votes
There is a working module for Drupal 8: Node Revisions Autoclean.

> This module allows to manage node's revisions store : according to admin's settings, older revisions are automatically deleted.
>
> You may choose how many revisions you want to keep for each node type. Latest drafts coming after a published revision are never deleted. You may also choose to delete revisions by date.
>
> For larger websites with many node, you may choose to delete revision by cron or a drush command (drush 9 only).

Do not expect it to run on normal cron runs, yet. But it can be set to run on updating nodes. Here is the issue for the cron, which I do not fully understand: https://www.drupal.org/project/node\_revisions\_autoclean/issues/2958655

# Answer
> 3 votes
Please inject always a storage in the proper way:

```
  # my_module.services.yml
  node_storage:
    class: Drupal\node\NodeStorage
    factory: entity_type.manager:getStorage
    arguments: ['node']
  my_service:
    class: Drupal\my_module\MyService
    arguments: ['@node_storage']

```

In this case you can already have in your class constructor the following:

```
class MyService {

  /**
   * @var \Drupal\node\NodeStorageInterface
   */
  private $storage;

  public function __construct(NodeStorageInterface $storage) {
    $this->storage = $storage;
  }

}

```

In this case your IDE will also easily list all of the available methods unlike with this solution:

```
\Drupal::entityManager()->getStorage('node')->revisionIds(node_load($nid));

```

Remember EntityTypeManager is in most of the case "too much" power: use only as much as you need but not more. Service configurations can help you with that.

---
Tags: nodes, 8
---


# Question
Title: How do I add an existing paragraph field to another content type programmatically
I have a paragraph field that is already used in a content type. I need to add that paragraph field to another content type using the same field that I was using in the previous content type. How do I do that?

# Answer
> 1 votes
Should be the same as with any other fields:

1. You go `Structure/Content Types/MyContentType`
2. Re-use an existing field: `Entity Reference Revisions: ..`
3. You click `Save and continue` and you apply your settings.

---
Tags: 8, nodes, paragraphs
---


# Question
Title: How to send an email to an Organic Group admin for every comment of their group?
Drupal 7.x Organic Groups / Rules 7.x-2.9

What is the best method to send an email to the 'Administrator Member' role of a group every time a comment is posted in their group?

I am looking to specify the exact groups that this rule works for.

# Answer
You can create a rule with:

* Add Event "After saving new comment" or "after udating an existing comment"
* Add action to the rule, under the "Organic Groups" section, there is a "Get group managers from group audience".
* Then you add a loop for this list, and then use the "Send email" from under "System" section.
> 2 votes

---
Tags: rules, organic-groups
---


title: Custom block and menu caching

text:
# Question
Title: Custom block and menu caching
I have a custom block building a menu. The cache works fine until a menu item is enabled/disabled in the menu edit, e.g.

admin/structure/menu/manage/main toggle the enabled checkbox and save.

The block does not reflect changes until the cache is cleared.

I have:

```
            '#cache' => [
                'tags' => [
                    'node_list'
                ],
                'contexts' => [
                    'url.path',
                ],
            ],

```

which picks up the url / menu text changes and also makes sure the block is valid for each node it is on \[i.e. not showing the same block content on every node, but this node's version\].

What tag do I need to make sure the cache is invalidated when menu item:enabled is toggled?

# Answer
You have to add the cache tag of the menu, in this case the main menu:

```
  '#cache' => [
    'tags' => [
      'config:system.menu.main',
      ...

```
> 3 votes

---
Tags: blocks, caching
---


# Question
Title: Error: Call to undefined function locale_translation_use_remote_source() in install_import_translations()
After I added a language, and set as default language, I get this error.

> Error: Call to undefined function locale\_translation\_use\_remote\_source() in install\_import\_translations()

I didn't enable the Locale module yet. I enabled only the Language module.

What do I have to do?

# Answer
> 1 votes
The error is caused from the fact `install_import_translations()` is calling a function that is provided from the Locale module (`locale_translation_use_remote_source()`), but since that module is not installed, the function is not found.

The Language module doesn't have the Locale module as dependency, so installing the first doesn't install the second. The opposite is true: One of the dependencies of the Locale module is the Language module.

I cannot say if this is caused by a bug on Drupal core that doesn't check the Locale module is installed before calling one of its functions, but installing the Locale module would resolve the issue. Once the Locale module is installed, Drupal will be able to find its functions, and you won't see that error again.

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


# Question
Title: Entityform view block not displaying on page
I can't seem to get Views-based blocks to show up on an Entityform page (Drupal 7). The View has a Contextual Filter of "Entityform Submission: Entityform submission ID". For the "When the filter value is not available" setting, I have "Provide default value: Content ID from URL" selected:

When I enter in an Entityform Submission ID in the Preview section, I get the results I'm after. However, when I place the Block on an Entityform page, it doesn't even show up.

What am I doing wrong?

# Answer
I solved my own problem by changing the "When the filter value is NOT available" setting to "Provide default value: Content ID from URL" and using the 2nd path component (which is the Entityform submission ID):

This works for me. But I can imagine a scenario where the ID is obscured from the URL and this wouldn't work.
> 0 votes

---
Tags: views, blocks
---


# Question
Title: How to get the language code when a language name is given?
We are creating nodes programmatically on submitting a form. The language of a node is an input value in the form. How can I get the langcode, when I have the Language name?

For example, user may type English. So i should convert it to "en"

If there an in-built function for that?

# Answer
You can do it with this code.

```
// Language to search.
$find = 'French';

// Getting all the available languages.
$languages = \Drupal::service('language_manager')->getStandardLanguageList();

$key = key(array_filter($languages, function ($array) use ($find) {
  if (array_search($find, $array) === FALSE) {
    return FALSE;
  }
  return TRUE;
}));

// If you have the devel module installed you can use the dpm function.
dpm($key);

```

Or, if you are on PHP 7.4+:

```
// Language to search.
$find = 'French';

$languages = \Drupal::service('language_manager')::getStandardLanguageList();
$langcode = key(array_filter($languages, fn ($lang) => in_array($find, $lang)));

```
> 4 votes

# Answer
Yes, the *language\_manager* service can give you a list of available languages for which you can get the corresponding language ID, as said in the other answer.
Just don't access the `LanguageManager` class directly as that is the wrong way to use a service provided by Drupal or third-party modules.

Since you are letting the users select a language from a form, instead of using a *textfield* element, you should use a *language\_select* element as in the following form builder code.

```
  $form['selected_langcode'] = [
    '#type' => 'language_select',
    '#title' => $this
      ->t('Language'),
    '#languages' => LanguageInterface::STATE_CONFIGURABLE | LanguageInterface::STATE_SITE_DEFAULT,
    '#default_value' => $config
      ->get('selected_langcode'),
  ];

```

Using that form element, the submission handler would get the language code for the language selected from the user with `$form_state->getValue('selected_langcode')`.

For more details about the form element, you can read New language\_select element in the Form API. For practical examples of uses of the form element, you can look at the uses of the *language\_select* element.
In particular, you could be interested on how to show a full list of languages, instead of a list of languages set in the site. The following code would do that.

```
  $form['selected_langcode'] = [
    '#type' => 'language_select',
    '#title' => $this
      ->t('Language'),
    '#languages' => LanguageInterface::STATE_ALL,
    '#default_value' => $config
      ->get('selected_langcode'),
  ];

```

For a full list of available constants, see the documentation for `LanguageInterface`.
> 2 votes

# Answer
Drupal 8 has a built-in function that lists all the language codes: `LanguageManager::getStandardLanguageList()`. My suggestion is to give the users a dropdown list of languages.

```
use Drupal\Core\Language\LanguageManager;
$standard_languages = LanguageManager::getStandardLanguageList();

foreach($standard_languages as $key => $val){
    if($val[0] == "English"){
        echo $key; //write your code

    }
}

```
> -2 votes

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


# Question
Title: header and menu is missing from Login module page--user--login.tpl.php
I am implementing Custom Login module but Header is missing...

My Directory is :

```
modules
  |
  --- module_name
          |
          --- css
          |
          --- module_name.info
          |
          --- module_name.module
          |
          --- templates

```

module\_name.module contains :

```
function module_name_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'user_login') {
        $form['name']['#attributes']['autofocus'] = 'autofocus';
        $form['name']['#attributes']['placeholder'] = t('Email');
        $form['pass']['#attributes']['placeholder'] = t('Password');
        // We don't really need descriptions to tell us what we already know...
        unset($form['name']['#description']);
        unset($form['pass']['#description']);

        // $form['#attached']['css'][] = drupal_get_path('module', 'module_name') . '/css/login.css';
    }

    // We don't want to change page titles on other pages.
    // Array of arg(1) url values on target pages.
    $pages = array('login', 'password');
    if (!in_array(arg(1), $pages)) {
        return;
    }

    switch ($form_id) {
        case 'user_login':
            drupal_set_title(t('Login'));
            break;

        case 'user_pass':
            drupal_set_title(t('Forgot your password?'));
            break;
    }
}

/**
 * Implements hook_theme_registry_alter().
 */
function module_name_theme_registry_alter(&$theme_registry) {
    $mod_path = drupal_get_path('module', 'module_name');

    $theme_registry_copy = $theme_registry;
    _theme_process_registry($theme_registry_copy, 'phptemplate', 'theme_engine', '', $mod_path);
    $theme_registry += array_diff_key($theme_registry_copy, $theme_registry);

    $hooks = array('page');
    foreach ($hooks as $h) {
        if (!isset($theme_registry[$h]['theme paths'])) {
            $theme_registry[$h]['theme paths'] = array();
        }

        _module_name_insert_after_first_element($theme_registry[$h]['theme paths'], $mod_path);
    }
}

/**
 * Function responsible for inserting a new element after the first one.
 */
function _module_name_insert_after_first_element(&$a, $element) {
    if (is_array($a)) {
        $first_element = array_shift($a);
        if ($first_element) {
            array_unshift($a, $first_element, $element);
        }
        else {
            array_unshift($a, $element);
        }
    }
}

```

templates/page--user--login.tpl.php contains:

```
<div  class="login">

  <div id="middle_part">
    <h2 class="title"><?php print $title; ?></h2>

    <?php print $messages; ?>
<?php print render($page['content']); ?>
</div>
  </div>

  </div>
</div>

```

Everything is ok, but Header and Menu is missing (as defined in my current theme) from HTML output (/user/login), any suggestion?

# Answer
> 1 votes
Your page--user--login.tpl.php is overriding the page.tpl.php. Print your header & menus regions/variables in the file 'page--user--login.tpl.php'.

---
Tags: theming, users, hooks
---


# Question
Title: Is there a way to add non indexed fields to a search api view?
I’m wondering if it’s possible to add non-indexed fields to a search API indexed view?

I want the standard flags fields to be available on the indexed search view. And I was thinking I could do this with relationships but nothing shows up as an option.

**EDIT:** I was using a taxonomy view until my needs required a more robust filtering system, hence the switch to search API. With facets, it gives me robust filtering options so I can segment my content better than taxonomy alone.

I am building a flashcard website and using Views to display the flashcards and Flags to allow users to mark the flashcards as complete once they memorize the card. This way it can be removed from the main view depending on the status of the flag. So if it isn't flagged it's in the flashcard View, and if they flag it, then it gets removed from the view and I have an attached view, where it will then be listed as memorized.

**I will need all of the standard Flags Views integration options to replicate what I was doing before with my taxonomy view. Otherwise, I will have to patch the Flags module or find an alternative to flags.**

# Answer
If you were using Drupal 7 and Apache Solr, you could get something like this with the Apache Solr Display module:

https://www.drupal.org/project/apachesolr\_display

The advantage here is that you can store rendered entity or entity json encoded object inside the Solr index, which allows you to access non-indexed fields. Otherwise you would need to load the node to access those fields.

I'm not sure if there is any analogous module for Drupal 8, but a similar approach might work.
> 0 votes

# Answer
From my understanding of the problem so far, try indexing the field which stores the relationship data. After that, you should most probably get an option to create a views relationship.

*Example:* If you have a taxonomy term reference at `field_categories`, then add the `field_categories` to the search index. Once done, you should get an option to create a relationship with the taxonomy term in the views UI.

A more detailed explanation of the problem will be helpful.
> 0 votes

---
Tags: views, search, flags
---


# Question
Title: Drupal t() function does not replace placeholders for me
Why would placeholders not be replaced?

For example, in the *Uninstall* page for modules, it shows the following.

>

It happens under the revisions tab as well.

>

# Answer
> 0 votes
It looks like electrokate installed a Pattern Lab starter theme for Drupal that has a mock of the `t()` function that acts as a placeholder for prototyping the front end layer. It only returns the input it was sent, so it "works" under Pattern Lab - but running it inside of Drupal will cause this issue.

```
/**
 * @file
 * Drupal translate filter.
 */
$filter = new Twig_SimpleFilter('t', function ($string) {
  return $string;
});

```

This is meant to aid in making a Pattern Lab prototype outside of Drupal, but taking advantage of functions you will expect to use inside of Drupal so it is "Drupal ready".

edit: I may have linked to the wrong starter theme, but I can’t navigate it on mobile.

---
Tags: 8
---


# Question
Title: Programmatically set the front page per site?
I have a site that is using a 'fake' multi-site instance (I think, someone else implemented it). We created 3 directories in `sites`:

`sites/site1
sites/site2
sites/site3`

and in each `settings.php` inside these directories it includes the original `settings.php` from the default directory.

I am overriding the theme successfully in these files by doing `$config['system.theme']['default'] = 'theme2';`

When I try doing `$config['system.site']['page']['front'] = '/node/239';` it works only on cache flush.

For example if I am on site 1 I see the front page set in the UI.
Then when I switch to `site2.example.test` I still see the default front page instead of what is on `/node/239`.
When I flush the cache, the reverse happens; site 2 homepage shows `/node/239` and so does site 1.

I have also tried setting this in an event listener:

```
public function kernel_request(Event $event) {
    $config = \Drupal::configFactory()->getEditable('system.site');
    $site_path = \Drupal::service('site.path');
    $site_path = explode('/', $site_path);
    $site_name = $site_path[1];

    if ($site_name === 'site2' && $event->getRequest()->getPathInfo() == '/') {
      $config->set('page.front', '/node/239')->save();
    }
    else {
      $config->set('page.front', '/home-content')->save();

    }
  }

```

This now does the right thing, but only after loading the page and then refreshing.

Could anyone tell me what the "correct" way of doing this would be that wont be cached?

# Answer
> 4 votes
Thanks to everyone for your responses.
I looked in to using the Domain module but am avoiding for 2 reasons:

* It is still in Alpha14 and this is going to be a business critical site
* I couldn't work out how to set the domain specific configurations

However, installing the Domain Module and looking at the README file pointed me in the right direction.

For anyone else who is looking to achieve setting a different Front Page per domain:

* I used the Drupal Console to generate an Event Subscriber for `Kernal.request`
* In the `getSubscribedEvents` method you need to set the weight to something greater than 30 which overrides the Page Cache and Dynamic Cache.

```
$events['kernel.request'] = ['kernel_request', '35'];

```
* I got the editable configuration for the site settings from

```
$config = \Drupal::configFactory()->getEditable('system.site');

```
* and the site name added in `sites.php` by doing:

```
$site_path = \Drupal::service('site.path');
$site_path = explode('/', $site_path);
$site_name = $site_path[1];

```
* Then added the logic:

```
if ($site_name === 'site2') {
  $config->set('page.front', '/node/239')->save();
}
else {
  $config->set('page.front', '/main-content')->save();
}

```

The Key thing I was missing was setting the ***Cache Context*** for sites.
You need to duplicate the `default.services.yml` from the `sites/default` directory and rename it to `services.yml` (if you don't already have this file).

Then you will need to add `url.site` to the `required_cache_contexts` array so that is becomes something similar to:

```
required_cache_contexts: ['languages:language_interface', 'theme', 'user.permissions', 'url.site']

```

Remember to flush the cache and this should work!

# Answer
> 1 votes
> a 'fake' multi-site instance

That's technical debt and someone has to swallow the bitter pill now to fix it.

Make it a real multisite and then set the front page per instance as usual.

I once had the same problem and I don't regret it for a second that I finally made it right.

1. Duplicate the database for every instance
2. Copy the `settings.php` file into every instance and adjust them
3. Copy the config directory for every instance
4. Copy the `default/files` directory into each instance.
5. Fix the `sites.php` file if necessary

Only thing I needed to pay a little bit more attention in the end were some broken file paths, especially the ones written directly in body texts. But that was it.

---
Tags: 8, configuration
---


title: Is "parent" supported in aliases?

text:
# Question
Title: Is "parent" supported in aliases?
Is the "parent" key supported in Drush 9? It isn't in the example file here https://github.com/drush-ops/drush/blob/master/examples/example.site.yml or `drush docs:aliases` and I am trying to get a bastion working off of the Drush 8 docs (https://docs.drush.org/en/8.x/bastion/).

Can anyone confirm it should pickup a "parent" key?

edit: I see here http://api.drush.org/api/drush/examples%21example.aliases.drushrc.php/master that "parent" was deprecated before the switch to YAML in Drush 9 so maybe it is called something else now. Not sure how to specify merging key values in YAML.

# Answer
> 3 votes
`parent` is not supported in Drush 9 aliases, but there are a couple of facilities that you can use.

Variables such as ${env.home} or ${foo.bar} can be used to inject environment and configuration values from Drush configuration into alias files.

An environment named `common` in any `sitename.site.yml` file will have its attributes copied into every environment defined in the same file.

---
Tags: drush, ssh
---


title: Equivalent method or "body onload"

text:
# Question
Title: Equivalent method or "body onload"
First, I have tried for several hours to weed through the various search results of the keywords above. I've found several things that seem to answer this but they're for Drupal 7; one of those was posted on 2012 and I am pretty sure things are gosh darn different now.

I am not a programmer, nor a web dev professional; I am just someone trying to update a very old site that worked fine but that needs to be re-freshen. I have some experience as a content manager with Drupal 6, but I have never got into coding, building modules, or editing template files. I am not afraid to copy a file, open it in an editor, change this or that, cut or paste, but I don't see myself being able to build a module to do this.

Maybe there's no way to do this "easily."

I want to replicate a Google map with a custom search feature and some other tweaks. It works nicely in the existing site and it is basically 3 parts: a `<script>code here</script>` in `<head>`, some HTML and script in the body, and the following markup for `<body>`.

```
<body onload="load(); curvycurvy()" onunload="GUnload()">

```

All I am hoping to do is properly add this code on my new Drupal 8 front page. I've used the Asset Injector module to add the bulk of the script to `<head>` and used `<front>` to restrict it to the front page. I have chosen PHP for the content and it seems to retain the script.

Is there a way to add this code above into the body? Failing that, is there a way to provide similar functionality?

I was hoping that the Asset Injector has some tools like, "Add to the Body Tag" or such, that would have been exactly what I need.

# Answer
This is fairly easy and covered well in the Javascript API section of the drupal docs.

Effectively you want a Javascript file that creates a Drupal behavior (this is automatically fired when the document is ready). Inside the behavior, just call `curvycurvy();`.

https://www.drupal.org/docs/8/api/javascript-api/javascript-api-overview

So, for starters...

```
Drupal.behaviors.initCurvy = {
  attach: function (context, settings) {
    curvycurvy();
  }
};

```
> 1 votes

# Answer
It's not really considered good practice, but since you are already using the Asset Injector Module, you could inject some jQuery to replace the existing code written in the body tag:

```
/* This replaces "<body onload="load(); curvycurvy()" */
$(document).on('load', function(){
   load();
   curvycurvy();
});

/* This replaces onunload="GUnload()"> */
$(window).unload(function() {
  GUnload();
});

```
> 0 votes

---
Tags: 8, javascript
---


title: main menu link as language switcher

text:
# Question
Title: main menu link as language switcher
I have 2 language and these situation:

* main menu -\> lang1 -\> link to www.foo.com/
* main menu -\> lang2 -\> link to www.foo.com/en

All sites when switch manually on browser the language, But my main menu link not work.

I have no space to place an other block with menu switcher on main menu bar.

I hope someone can send me in right direction because I spent 8 hour around these without solutions?

# Answer
after long investigation and test I think there is no way to make the "language module" work correctly if all the language codes have not been declared in the configuration, so that every language has the code after the base\_path. Using base\_path for the primary language and code for the secondary (base\_path / language\_code /) creates confusion to the "language module" that results in unexpected results. Alias url and url edirect can not make up for the lack. It would be necessary to create a special module to solve the situation and while having seen some code in the working web, I do not think it's a good idea to use it with the core 8 and beyond. The "language switcher" module, on the other hand, works well, but to make it integrated into the main menu, you still need to write custom code. In short, all languages, the primary and the others must be dicated in the configuration in the classic way: base\_path / language\_code /. There is no way out.
> 0 votes

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


title: Where do I place helper files?

text:
# Question
Title: Where do I place helper files?
I would like to place some (PHP)functions in a helper files, which requires across modules and themes.

Do I have to create a new module or I can place a simple helper file with list of common functions, what is the best practice for these kind of functions in drupal 8 ?

# Answer
> 0 votes
Yes, create a utility module, so your consumer modules can declare a dependency to the utility module in their `.info.yml` file. Optionally to keep the admin UI clean you could use `hidden: true` in the utility module's `.info.yml`

(I assumed you are speaking of a very drupal-specific helper lib, not some general purpose library like e.g. Guzzle that would go into composer)

---
Tags: 8
---


# Question
Title: How to add javascript with #attached in a node which contains a specific paragraph bundle
I need to attach js in all nodes with a specif paragraph bundle. I know how to do this with drupal\_add\_js, but I prefer don't use it to prevent cache problems.

I am trying with hook preprocess\_entity but I don't get it, I don't know how to use the \["#attached"\]

```
function THEME_preprocess_entity(&$variables) {
  if (isset($variables['paragraphs_item']->bundle) && variables['paragraphs_item']->bundle == "XXXXX") {
   $variables["elements"]["#attached"]['js'][] = array(
                'type' => 'file',
                'data' => 'myfile.js',
              );
      }
    }

```

What am I doing wrong?

# Answer
Finally I got, I have to add \['content'\] before \['#attached'\]

```
function THEME_preprocess_entity(&$variables) {
  if (isset($variables['paragraphs_item']->bundle) && variables['paragraphs_item']->bundle == "XXXXX") {
    $variables["content"]["#attached"]['js'][] = array(
       'type' => 'file',
       'data' => 'myFile.js',
    );
  }
 }

```
> 0 votes

# Answer
Try this code for attaching

```
$variables['#attached']['js'][] = 'myfile.js';

```

Or

```
$variables['#attached']['library'][] = 'myfile.js';

```
> 0 votes

---
Tags: 7, javascript
---


# Question
Title: How to stop webform from sending an email
**I'm using Drupal 7.12 / Webform 3**

How do I stop email from being sent upon a webform submission? I want to do this conditionally so I need to use a hook. I still want everything else to go through correctly (i.e. confirmation page, db entry for submission).

I see that there are these lines in `function webform_client_form_submit($form, &$form_state)`

```
if (!$is_draft && !$form_state['values']['details']['finished']) {
    $submission = webform_get_submission($node->webform['nid'], $sid, TRUE);
    webform_submission_send_mail($node, $submission);
  }

```

How do I hook into that and stop it?

# Answer
If you go the end of the function webform\_submission\_send\_mail() inside the file webform.submissions.inc (inside weform module's *include* directory), you'll notice that the webform module using the function drupal\_mail() to send the mail.

So a better place to change the behavior of the mail from being sent (*alter* in Drupal terms) is hook\_mail\_alter(), which is used to alter an email message created by using `drupal_mail()` function.

Implementation of the *hook* to stop the e-mails:

```
function MODULE_mail_alter(&$message) {
  //You can do your conditional check here and depending on that
  //you can set the value of $message['send'] to false to stop the mail from being sent.
  //place the line below inside conditional loop, or else it'll stop every mail from being sent ;-)
  $message['send'] = FALSE;
}

```

**Note:** This *hook* will only work if the mail is generated by `drupal_mail()`. If you're sending mail by some other menthod, it'll not be invoked. But, by default Webform module uses `drupal_mail()` as mentioned earlier, so there's nothing to worry :-)
You'll also need to clear the caches to make the change effective.
> 8 votes

# Answer
You can also use webform with Rules and Webform Rules. Are your conditions something complicated that Rules cannot implement?

> This module adds rules integration on webforms.
> 1 votes

# Answer
You should just remove all recipients on here:

```
yoursite.com/node/XXX/webform/emails

```

when there are no recipients no emails will be sent.
> 0 votes

# Answer
you even do not need override webform\_client\_form\_submit function, because 'webform\_client\_form\_submit' function works with $form\['#node'\]-\>webform\['emails'\] array, which you can modify in form\_alter hook. (unset your email for some specific condition). I've tested it on webform 4v, maybe for 3v object can have other structure, but i think it also have to work
> 0 votes

# Answer
I had to do this in hook\_webform\_submission\_insert. I just looped through the emails and changed their status. In my case I wanted to enable them so set them to 1.

```
   foreach ($node->webform['emails'] as $key => $email) {
    $node->webform['emails'][$key]['status'] = 1 // or 0 to disable;
  }

```
> 0 votes

# Answer
I used the same approach as Cameron, by using the insert hook. Setting the status for each email did not work for me however.

I managed to get it to work by unsetting the emails I did not want to go out.

```
foreach ($node->webform['emails'] as $key => $email) {
  unset($node->webform['emails'][$key]);
}

```
> 0 votes

---
Tags: 7, webforms
---


title: Decimal number and Charts Module

text:
# Question
Title: Decimal number and Charts Module
I installed Charts with Google Charts in Drupal 7. Everything is ok, but when I have to use decimal numbers, with number 0.5 or 0.8, it appears to me .0 or .8 both on the vertical axis of my column chart and on the graph itself. Why?

# Answer
> 0 votes
last night I'v found the problem and solve.

change the row in the file "charts\_google.inc" row n. 223

from $format = $prefix . '#' . $decimal\_count . $suffix;

to

```
  $format = $prefix . '#0' . $decimal_count . $suffix;

```

---
Tags: 7, views, charts
---


# Question
Title: how to display data in view for specific content base on permission
I want to create the view where content of specific type will be visible according to given permission for current user's role.

For Example:I have created a role and given it the permission for create, edit ,delete Article Content Type. so the view should display all the nodes for article. This should be applicable on multiple content types also.

Summary : View should display only nodes for which user has permission for create,edit,delete.

# Answer
> 0 votes
Create your view, in middle column, in `Permissions: View Published Content`click on it and select `Role`. Specify the role you want.

---
Tags: views, users
---


# Question
Title: InvalidArgumentException: Invalid translation language (fr) specified
I'm currently trying to translate my twig template to the current language and at this moment I'm getting the following error

> InvalidArgumentException: Invalid translation language (fr) specified. in Drupal\Core\Entity\ContentEntityBase-\>getTranslation() (line 872 of /Applications/XAMPP/xamppfiles/htdocs/iom/core/lib/Drupal/Core/Entity/ContentEntityBase.php).

Here is a snippet of code that I'm currently working on

```
// Page-level pre-processing
function iom_preprocess_page(&$variables) {

    $language = \Drupal::languageManager()->getCurrentLanguage();
    $variables['lang_code'] = $language->getId();
}

```

---

```
{% if (language.getId() == 'fr')  %}

    <li class="tab">{{ tab_label.entity.field_tab_title.entity.translation('fr').label }}</li>

{% else %}

    <li class="tab">{{ tab_label.entity.field_tab_title.entity.label }}</li>

{% endif %}

```

---

Somehow this part right here is what seems to be causing the error even though the language is currently correct

```
<li class="tab">{{ tab_label.entity.field_tab_title.entity.translation('fr').label }}</li>

```

# Answer
> 2 votes
Should check on `lang_code` the variable you already passed from preprocess, not `language.getId()` try something like that:

```
{% if lang_code == 'fr' and tab_label.entity.hastranslation(lang_code) %}
  <li class="tab">{{ tab_label.entity.translation(lang_code).field_tab_title.entity.label }}</li>
{% else %}
  <li class="tab">{{ tab_label.entity.field_tab_title.entity.label }}</li>
{% endif %}

```

---
Tags: theming, i18n-l10n
---