title: Add /usr/login welcome screen

text:
# Question
Title: Add /usr/login welcome screen
Drupal8 newbie here (using better login and system caching is on),

I wanted to just add a php page before the login page that says something like :

```
"Please follow the rules of our site, click accept button to agree and login in:"

                                   [Accept Button]

```

After pressing the button it forwards you to the normal /user/login page. Any tips would be great, it seems harder than it should be, we really don't want to use JQuery/JS.

# Answer
You can do this by creating a custom module: Example:

1. MODULE\_NAME(mydata)
2. creat routing file. (mydata.routing.yml):

```
     mydata.redirect_form:
       path: '/user/redirect'
       defaults:
         _form: '\Drupal\mydata\Form\RedirectForm'
         _title: 'Redirect User'
       requirements:
         _permission: 'access content'

```
3. Create .module file (mydata.module):

```
use Symfony\Component\HttpFoundation\RedirectResponse;
use Drupal\Core\Url;

function mydata_preprocess_page(&$var){
    if(empty($_SESSION['terms_accepted']) || $_SESSION['terms_accepted'] != 'ok'){
        if (\Drupal::routeMatch()->getRouteName() == "user.login"){
            $path = Url::fromRoute('mydata.redirect_form', [], ['absolute' => TRUE])->toString();
            $response = new RedirectResponse($path);
            return $response->send();

        }
    }
}

```
4. Create file in module folder src/Form/RedirectForm.php:

```
namespace Drupal\mydata\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Symfony\Component\HttpFoundation\RedirectResponse;

class RedirectForm extends FormBase {

    public function getFormId() {
        return 'redirect_form';
    }

    public function buildForm(array $form, FormStateInterface $form_state) {
        if(!empty(@$_SESSION['terms_accepted']) || @$_SESSION['terms_accepted'] == 'ok'){
            $path = Url::fromRoute('user.login', [], ['absolute' => TRUE])->toString();
            $response = new RedirectResponse($path);
            return $response->send();
        }

        $form['test'] = [
            '#type' => 'item',
            '#markup' => t('Please Follow the rule of our site,click accept button to agree and login-in: '),
        ];

        $form['submit'] = [
            '#type' => 'submit',
            '#value' => 'Accept',
        ];

        return $form;

      }

    public function submitForm(array &$form, FormStateInterface $form_state) {
        $_SESSION['terms_accepted'] = 'ok';
        if($_SESSION['terms_accepted']){
            $form_state->setRedirect('user.login');
        }
    }
}

```
> 1 votes

---
Tags: 8
---


# Question
Title: Hiding group_group field programmatically
I am trying to hide the group\_group (request membership) field for organic groups based on a radio button. Here is what I have done that doesn't work:

```
/**
 * Implements hook_form_alter().
 */
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  $menu = menu_get_item();
  $path = drupal_get_path_alias();

  $node = node_load($menu['page_arguments'][0]->nid);

  // field_show_group_group is radio button
  if($item['field_show_group_group'][LANGUAGE_NONE]['value'] === 0) {
    dsm("Just show the subscribe button - NOTHING to do.");
  }
  else {

    dsm("hide button");
    $instance = field_info_instance('node', 'group_group', 'community');
    $instance['widget']['settings']['og_hide'] = FALSE;
    $instance['settings']['behaviors']['og_widget']['access_override'] = FALSE;
    unset($instance['widget']['settings']['og_hide']);
    unset($instance['settings']['behaviors']['og_widget']['access_override']);
    $form['group_group']['#access'] = FALSE;
    $form['group_group'][LANGUAGE_NONE][0]['value']['#access'] = FALSE;
    unset($form['group_group']);
    unset($form['group_group']);
    $menu['page_arguments'][0]->group_group['und'][0]['value'] = 0;
    unset($menu['page_arguments'][0]);
    $item['group_group'][LANGUAGE_NONE][0]['value']['#access'] = FALSE;
    unset($item['group_group'][LANGUAGE_NONE][0]['value']['#access']);
    $node->group_group[LANGUAGE_NONE][0]['value']['#access'] = FALSE;

```

}

These are all possibilities I couldn't think of, which of course for some reason don't work. I searched the whole internet for this including drupal.org, drupal.stackexchange, google and stackoverflow. Can you help?

# Answer
You should be able to hide the group\_group field with the `$form['group_group']['#access'] = FALSE;` this is used by the Hide checkbox on the field settings page and this is how it works.

However, if you testing as an anonymous user maybe you have this issue: https://www.drupal.org/project/og/issues/2278003 there's a patch which fixes the access itself.
> 0 votes

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


# Question
Title: CSS still requiring clearing cache after following steps to switch caching off
I have followed the steps detailed in this tutorial and many others -\> https://knackforge.com/blog/rajamohamed/disable-drupal-8-cache-during-development

I have copied and renamed the sites/example.settings.local.php file as sites/default/settings.local.php

Opened settings.php file in sites/default directory and uncomment these lines:

```
if (file_exists(__DIR__ . '/settings.local.php')) {
  include __DIR__ . '/settings.local.php';
}

```

I have uncommented the following lines in settings.local.php to disable the render cache and dynamic page

```
$settings['cache']['bins']['render'] = 'cache.backend.null';
$settings['cache']['bins']['dynamic_page_cache'] = 'cache.backend.null';

```

I have opened development.services.yml in the sites folder and added the following lines (to disable twig cache)

```
parameters:
  twig.config:
    debug : true
    auto_reload: true
    cache: false

```

I have then cleared cache, this has worked for twig it seems as I am able to make changes in my page.html.twig and these update on a standard browser refresh.

However, any changes to by CSS files are requiring a clear cache every time, slowing development down quite a lot over time.

Hoping for some help here.

# Answer
> 1 votes
Written by @Clive in the comments

> Are you using chrome? Asset caching got way more aggressive recently for some reason, if you're using it try opening the Network tab in dev tools and selecting "Disable cache"

This solved me the problem.

---
Tags: 8, caching
---


title: Date format in another language

text:
# Question
Title: Date format in another language
I have a multilingual site. English and Dutch are the languages. I need to display date format in Dutch, ie  **I need to display a timestamp in Dutch(nl), as 16 oktober 2017.** Tried the below code and *format\_date()*, but didn't do the trick.

```
$date = $node->getCreatedTime();
\Drupal::service('date.formatter')->format($date, 'custom', 'd F Y', $timezone = NULL, $langcode = 'nl'); //not working for me

format_date($timestamp, $type = 'medium', $format = '', $timezone = NULL, $langcode = 'nl');

```

Above code returned date in "en" language. Am I missing something here.. Thanks..

# Answer
You need write something like:

```
$date = $node->getCreatedTime();
\Drupal::service('date.formatter')->format($date, 'custom', 'd F Y', NULL, 'nl');

```
> 5 votes

# Answer
The Drupal way of handling and translating Dates is through `Configuration > Regional and language > Date and time formats`, as Hudri mentioned in his comment.

## The same date and time Pattern between languages

What you should do depends on what pattern you want your date to be in English, if it should also be `'d F Y'` as in Dutch. If yes, then you should edit the relevant Date format through the interface. Content types use `Medium` as default for the “Submitted by” so edit that to keep things simple.

I expect you'll have the date and time related terms already translated into Dutch, so you'll get `oktober` and not `October` on the Dutch side.

## Different date and time Pattern between languages

If you want the Pattern of the same Date format to be different between laguages, for example you want English to be “10/16/2017” with Dutch “16 oktober 2017” you need to translate the Date format Pattern.

What is important to mention is that you need to have the **Configuration Translation** module enabled to be able to translate Date format Patterns. This will add the `Translate` link to the Operations button drop-down:

This enables you to have a different **Pattern** for different Languages under the same Date format.

Don't forget to Flush cache if you don't see the changes on existing content!

## Code manipulation

The format\_date() is Depricated, more info: Date formats API changes, public function DateFormatter::format.
> 4 votes

# Answer
You dont need custom code for it, every string can be translated via the translation interface.

Check this answer https://drupal.stackexchange.com/a/139407/3776
> -1 votes

---
Tags: 8
---


# Question
Title: How do I add the ability to change font size in CKEditor?
I'm trying to install the CKEditor Font Size Module in my my editor. I installed the module via `composer` and then proceeded to copy the `font/plugin.js` file from the Font Plugin's page into `libraries/` in my document root, per the instructions.

I also threw in a `console.log()` call into the `font/plugin.js` file to make sure it was loading. I modified the configuration of the Basic HTML editor to include the font size and family buttons in the toolbar on the `/admin/config/content/formats/manage/basic_html` page of my site. When I go to create a piece of content that uses the Text Editor, I don't see the font/size buttons I've configured.

Checking the Javascript console, I see my log message so I know the `font/plugin.js` file is being loaded. There are no error messages in the console. **Why would the buttons not be showing up in this case?**

# Answer
> 2 votes
Kevin's comment was spot on and it was in fact the Basic HTML configuration that was preventing the button from rendering. Specifically, the filter "Limit allowed HTML tags and correct faulty HTML" was the issue. The buttons rendered correctly in Full HTML mode so that was the hint.

In the filter configuration at the bottom of the `/admin/config/content/formats/manage/basic_html` page, I modified the allowed tags. By default the filter allows plain `span` tags without any attributes. However, this plugin uses span tags with inline `style` attributes. As a result, I had to change `<span>` to `<span style>` in Allow Tags list.

I can now see the font and size buttons in the editor, and using the tool injects HTML like the following:

```
<p>The <span style="font-size:72px;">Quick red</span> fox jumps over the lazy brown dog</p>

```

---
Tags: 8, wysiwyg, plugins
---


title: Create styled image programmatically

text:
# Question
Title: Create styled image programmatically
I have a module that create custom PDF with multiple selected nodes and I use the below function to create the link to styled images:

```
$file = File::load($img_id);
$imagesPath[] = ImageStyle::load('550x300')->buildUrl($file->uri->value);

```

Unfortunately, the image itself is not created, only the link, which is ok if I display it on a simple webpage because Drupal will create it on the fly when needed but on a PDF it cause errors because the image it not found before the PDF could be displayed.

Is there a programmatically way to create this image ?

Thanks.

# Answer
> 18 votes
You need to execute `createDerivative()` on `ImageStyle`.

```
$image_style = ImageStyle::load('550x300');

$file = File::load($img_id);
$image_uri = $file->getFileUri();
$destination_uri = $image_style->buildUri($file->uri->value);
$image_style->createDerivative($image_uri, $destination_uri);

```

For Drupal 7 there is `image_style_create_derivative()`:

```
$style = image_style_load('550x300');

$file = file_load($img_id);
$image_uri = $file->uri;
$destination = image_style_path($style['name'], $image_uri);
image_style_create_derivative($style, $image_uri, $destination);

```

# Answer
> 4 votes
This can be achieved with Image Style Warmer module which is available for D8. Worked perfectly for me! This might help other people, who are trying to find a solution.

> The Image Style Warmer module provides options to create image styles during upload or via queue worker. So configured image derivates already exists when they are requested.
>
> * Pre-generate configured image styles on image upload or crop change.
> * Pre-generate configured image styles via queue worker.

---
Tags: 8, media
---


title: Prevent underscores from removing text?

text:
# Question
Title: Prevent underscores from removing text?
Drupal seems to be removing all text prior to an underscore in my form. This is in the Form.php file of my module implementing Google CSE, so I cannot change the attribute name.

```
if (array_key_exists('search_broadness', $get_results) && $get_results['search_broadness'] == 'narrow') {
  $block .= 'data-as_sitesearch="' . $gcse_narrow_search_query . '"';
}
$form['search']['results'] = array(
  '#type' => 'item',
  '#markup' => $block,
  '#allowed_tags' => ['script', 'div'],
)

```

And this is the output, note that the data-as\_sitesearch is shortened to sitesearch.

```
<div class="gcse-searchresults-only" sitesearch="https://www.example.com/drupal8_gcse/"></div>

```

The Drupal Google CSE module does not have this feature, so I cannot use that. #markup in Drupal 7 worked to get around this, but not in Drupal 8. Is there a workaround to bypass this sanitation?

# Answer
I'm struggling to understand what that code is trying to do; I'm assuming your end goal is to render either this:

```
<div class="gcse-searchresults-only"></div>

```

Or this, if the condition passes:

```
<div class="gcse-searchresults-only" data-as_sitesearch="https://www.example.com/drupal8_gcse/"></div>

```

But I don't see how the code sample would ever to get to even the result in your question. There's no mention of a `<div>`, and if `$block` contains the opening `<div...`, then you've forgotten to close the opening tag and provide a closing tag after concat'ing the attribute string.

To make the whole thing easier (and a bit cleaner), you can use `html_tag` instead:

```
$form['search']['results'] = [
  '#type' => 'html_tag',
  '#tag' => 'div',
  '#attributes' => ['class' => ['gcse-searchresults-only']],
  '#value' => '',
];

if (array_key_exists('search_broadness', $get_results) && $get_results['search_broadness'] == 'narrow') {
  $form['search']['results']['#attributes']['data-as_sitesearch'] = $gcse_narrow_search_query;
}

```
> 0 votes

---
Tags: 8, forms, search
---


title: Define module as feature

text:
# Question
Title: Define module as feature
Creating a module with Drupal Composer asks me:

> Define module as feature (yes/no)

What does it mean?

# Answer
That option will add some code to the generated module to make it a Feature module - a module that provides some exportable configuration.

More info: https://www.drupal.org/docs/8/modules/features/creating-and-configuring-bundles Source: https://github.com/hechoendrupal/drupal-console/blob/master/src/Generator/ModuleGenerator.php#L94
> 6 votes

# Answer
It just adds a file with the name of the feature bundle, and the feature bundle is nothing but a way to group features.

With this file your module will appear on the features list.
> 3 votes

---
Tags: console
---


# Question
Title: Theme Image Style for image located in module directory
Probably coming at this from too much of a Drupal 6 view point but...

How do I theme an image in a given image style when that image lives in a module folder? This is driving me batty and I know I'm just missing something simple.

Here is some example code showing what I'm trying to do:

```
$file_uri = 'public://sites/all/modules/my_module/logo.jpg';
$data['logo'] = theme('image_style', array('style_name' => 'medium', 'path' => $file_uri));

```

Even if I use file\_build\_uri(), I end up with a path to a file that doesn't exist. If I move the image to the files directory and change the $file\_uri to 'public://logo.jpg', it works just fine.

Do I need to copy the image to the files directory as part of the module code? If so, isn't this ridiculous?

What am I missing? Is there documentation on how to do something like this? I've spent over an hour mining the Drupal documentation and came up completely dry.

# Answer
Unfortunately that's by design. From the `theme_image_style()` docs' description of the acceptable parameters:

> path: The path of the image file **relative to the Drupal files directory. This function does not work with images outside the files directory nor with remotely hosted images**. This should be in a format such as 'images/image.jpg', or using a stream wrapper such as 'public://images/image.jpg'.

Emphasis mine.

It seems the image style system only works in the context of the public files directory (maybe private too, I'm not sure).

I ran into a similar situation recently and ended up having to code it myself (although I borrowed a lot from the core image module).
> 4 votes

# Answer
I just came across this and had to write the code to handle this.

This effectively clones `theme_image_style()` to create image derivatives during execution of the page request. Generation bypasses the security issues that would otherwise normally trigger a 404, but that also means a slower page the first time the page is visited.

I am only using the public file schema, but I would expect this to fail with the private file schema based styles.

```
    /**
     * Implements hook_theme().
     */
    function MODULE_theme() {
      return array(
        'remote_image_style' => array(
          'variables' => array(
            'style_name' => NULL,
            'path' => NULL,
            'width' => NULL,
            'height' => NULL,
            'alt' => '',
            'title' => NULL,
            'attributes' => array(),
          ),
        ),
      );
    }

    /**
     * Returns HTML for an image using a specific image style.
     *
     * Clones theme_image_style() with the additional step of forcing the creation
     * of the derivative to bypass any 404 issues.
     */
    function theme_remote_image_style($variables) {
      // Determine the dimensions of the styled image.
      $dimensions = array(
        'width' => $variables['width'],
        'height' => $variables['height'],
      );
      image_style_transform_dimensions($variables['style_name'], $dimensions);

      $variables['width'] = $dimensions['width'];
      $variables['height'] = $dimensions['height'];

      $image_style_dest_path = image_style_path($variables['style_name'], $variables['path']);
      if (!file_exists($image_style_dest_path)) {
        $style = image_style_load($variables['style_name']);
        image_style_create_derivative($style, $variables['path'], $image_style_dest_path);
      }
      $variables['path'] = file_create_url($image_style_dest_path);
      return theme('image', $variables);
    }

```
> 9 votes

# Answer
`theme_image_style()` accepts a URI using PHP's stream wrappers and not real paths.

`input://` is a PHP's stream wrapper, whereas `public://`, `private://` and `temporary://` are Drupal's stream wrappers for representing the `sites/default/files`, private and temporary folders.

If you definitely need to use an image style with an image found in a module, you might want to check the system\_stream\_wrapper module which adds the **`module://`**, `theme://`, `profile://` and `library://` stream wrappers.

Notice: It may be irrelevant to the current question but since it was mentioned in other posts, I would like to also point to the remote\_stream\_wrapper module which *adds support for any URL using http://, https://, or feed://*. As mentioned though, *these stream wrappers are read-only and cannot perform any writing operations* but I believe it could be used with `image_style_url()` and related functions like `theme_image_style()`.
> 2 votes

---
Tags: 7, media
---


# Question
Title: How to programmatically get the field cardinality
Is there any way to get the number of paragraphs' repeating limit for the entity's field which those paragraphs depends on?

I'm writing a code which creates paragraphs according to the data taken from a CSV data and and insert their target ID (and target revision ID) into user fields programmatically.

The repeating limits of paragraphs for each user field differs. Some user fields allow paragraphs to repeat only a few times and others expect them to repeat 10 times.

So if my guess was correct it would be useful if I can get the number when collecting data from CSV and that's why I'm asking.

# Answer
Thanks for the comments, I figured out a way to get the number(cardinality). Hope it helps someone.

```
(array) $user_fields = \Drupal::service('entity_field.manager')->getFieldDefinitions('user', 'user');

foreach ($user_fields as $user_field_name => $user_field_definition) {
    (array) $cardinality = $user_field_definition->get('fieldStorage')->get('cardinality');
}

```
> 1 votes

---
Tags: 8, paragraphs
---


# Question
Title: Adding template suggestion for twig based on page and content type
Actually twig only suggest templates files name like this:

```
<!-- FILE NAME SUGGESTIONS:
   * html--node--20.html.twig
   * html--node--%.html.twig
   * html--node.html.twig
   x html.html.twig
-->

```

But I would have 2 kinds of template suggestion (like on my D6 website): One based on page + content type : page--CONTENT-TYPE.html.twig And other based on nodes + content-type : node--CONTENT-TYPE.html.twig or page--node-CONTENT-TYPE.html.twig

Actually I have a function in my .theme file like this but nothing change about suggestions:

```
function starterpf_d8_2019_theme_suggestions_page_alter(&$suggestions, $variables) {
  $path = \Drupal::requestStack()->getCurrentRequest()->getPathInfo();
  if ($path != '/') {
    $path = trim($path, '/');
    $arg = str_replace(["/", '-'], ['_', '_'], $path);
    $suggestions[] = 'page__' . $arg;
  }
}

```

Code found here

Thanks for help

EDIT: after exploring the output HTML, I get the page suggestions like this:

```
<!-- FILE NAME SUGGESTIONS:
   x page--front.html.twig
   * page--node.html.twig
   * page.html.twig
-->

```

So, can I add different kind of suggestions with putting together part of your codes ? Like this:

```
function starterpf_d8_2019_theme_suggestions_page_alter(&$suggestions, $variables) {
  $path = \Drupal::requestStack()->getCurrentRequest()->getPathInfo();
  if ($path != '/') {
    $path = trim($path, '/');
    $arg = str_replace(["/", '-'], ['_', '_'], $path);
    $suggestions[] = 'page__' . $arg;
  }
  #Suggestions pour les nodes
   $node = \Drupal::routeMatch()->getParameter('node');
  if ($node instanceof \Drupal\node\NodeInterface) {
    $suggestions[] = 'page__' . $node->bundle();
    $suggestions[] = 'page__node_' . $node->bundle();
  }

  #Suggestions pour les types de contenus
   if ($node = \Drupal::routeMatch()->getParameter('node')) {
    $content_type = $node->bundle();
    $suggestions[] = 'page__'.$content_type;
  }
}

```

And if I only want to create a file like `node--CONTENT-TYPE.html.twig` instead of a page one ? Interesting in use of `node--CONTENT-TYPE-nid.html.twig` too. And what would be better to use ? Knowing that I include field datas inside template to theme easily them ? In some use cases I will need to theme depending taxonomy term, is this native with D8 ?

# Answer
> 1 votes
Try this out:

```
/**
 * Implements hook_theme_suggestions_page_alter().
 */
function myModule_theme_suggestions_page_alter(&$suggestions, $variables) {
  $node = \Drupal::routeMatch()->getParameter('node');
  if ($node instanceof \Drupal\node\NodeInterface) {
    $suggestions[] = 'page__' . $node->bundle();
    $suggestions[] = 'page__node_' . $node->bundle();
  }
}

```

# Answer
> 0 votes
`hook_theme_suggestions_page_alter` modifies suggestions for `page.html.twig`, if you want to change suggestions for `html.html.twig` you need to use `hook_theme_suggestion_html_alter`

```
function starterpf_d8_2019_theme_suggestions_html_alter(&$suggestions, $variables) {
  $path = \Drupal::requestStack()->getCurrentRequest()->getPathInfo();
  if ($path != '/') {
    $path = trim($path, '/');
    $arg = str_replace(["/", '-'], ['_', '_'], $path);
    $suggestions[] = 'html__' . $arg;
  }
}

```

# Answer
> 0 votes
Try this:

```
/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function THEME_NAME_theme_suggestions_page_alter(array &$suggestions, array $variables) {

  if ($node = \Drupal::routeMatch()->getParameter('node')) {
    $content_type = $node->bundle();
    $suggestions[] = 'page__'.$content_type;
  }
}

```

Found here

---
Tags: 8, theming
---


title: Get arbitrary user entity with tokens

text:
# Question
Title: Get arbitrary user entity with tokens
Is there a way to retrieve an arbitrary user entity via tokens inside a node field?

## For example:

Let's say I have a field name `Source`, which contains a reference to an external news publication.

I have a user on my site named "Jane Doe".

I want to be able to put something like this in the source field. The example is a little fudged b/c I don't think Tokens has a "link" type token, but the question is more about getting data for an arbitrary user:

> New York Times, citing \[user:link:Jane Doe\].

And have that rendered as

> New York Times, citing Jane Doe.

## What I have tried

I've attempted this in the node body field (using the `token_filter` module).

I can get data for the current user with, such as with the token `[current-user:url]`.

But I haven't figured out how to get data for an arbitrary user.

I've tried:

* `[user:url:1]`
* `[user:url 1]`

# Answer
> 0 votes
There isn't a token that, given a user ID, would return data about that user account. *current-user* returns data about the currently logged-in user, while *user* returns data about the user account passed to the function (in Drupal 7, or the method in Drupal 8) that replaces tokens with their values: `token_replace()`.

It would be possible, for a module, to implement a token that returns data about every user accounts. With such a module, for example, *users:1:name* could return the username for the user account #1, while *users:2:name* would do the same for the user #2.

---
Tags: tokens
---


# Question
Title: How to set a multi line value from drush vset
I was trying to add a value to the drupal antibot antibot\_form\_ids variable.

```
drush vget antibot_form_ids

```

returns a string separated by /r/n Adding just a value to this string isn't just enough. If you do a
`drush vset antibot_form_ids 'webform_*\r\nuser_login\r\n`
and so on you end up with exactly this value in the form field of the config area.

So how can it be done?

# Answer
> 1 votes
Well, I just put my drush code in a text editor like this:

```
drush vset antibot_form_ids "webform_*
user_login
any_other_form
even_more_values" -y

```

Then copy & paste the whole statement to your command line and voila the values are set correctly.

---
Tags: 7, drush, configuration
---


# Question
Title: Hook to trigger when a field collection item is being deleted
I have create a module and I am using the following hook implementation.

The code works on success, but how do I prevent or stop further processing when I get *failed* as status?

```
mymodulename_field_collection_item_delete($field_collection_item) {
   $itemID = entity_id('field_collection_item', $field_collection_item);
   $fc = entity_load_single('field_collection_item', $itemID );
   $pid = $fc->field_product_guid['und'][0]['value'];
   $responseAPI = json_decode(deleteProductRequestAPI($pid,"DELETE"), true);
   if($responseAPI['status']=='success'){
     drupal_set_message(t('Is successfully deleted.'));
   }else{
     drupal_set_message(t('Failed to deleted.'));
   }
   die;
}
// here curl request sending
functin deleteProductRequestAPI($pid,$method){
  // here i have written code for send request and will
  // get response in status as "success" or "failed".
}

```

The field Collection name is *Products* and the content type is *Brands*.

# Answer
> 0 votes
What you should do instead of an API call on delete is create a job with the QueueAPI in Drupal to create a job for processing later. In that job, pull the ID from the record (stored in the job) and do the API call. If the status failed, requeue the job.

I can’t write all the code out for you but there are plenty of QueueAPI examples for D7 out there.

https://api.drupal.org/api/drupal/modules%21system%21system.queue.inc/group/queue/7.x

and

https://rbayliss.com/blog/drupal-queue-api/

Are great starting points.

You could then create a custom Drush command that processes these jobs as fast as you desire. Note the section in rovs post that deals with “failed” states of a job and not removing it from the queue. That is key.

This will let Drupal function normally and defer errors in the remote system to you to work through.

---
Tags: entities
---


# Question
Title: Anyone manage to work entity metadata wrapper with profile2 entity?
Code:

```
$profile = profile2_load_by_user($account);
$profile = $profile['main'];

$wrapper = entity_metadata_wrapper('profile2_type', $profile);

$wrapper->field_first_name->set(devel_generate_word(mt_rand(6, 12)));

```

I'm sure that `$profile` is Profile object. Beside 'profile2\_type' I tried 'profile', 'profile2' but got error too.

Current error:

> Unknown data property field\_first\_name.

# Answer
```
$profile = profile2_load_by_user($account);
$wrapper = entity_metadata_wrapper('profile2', $profile);

```
> 0 votes

# Answer
The problem is that `profile2_load_by_user()` returns an array of all user profiles by default, whereas `entity_metadata_wrapper()` needs a single entity object.

Try loading a single profile:

```
$profile = profile2_load_by_user($account, 'profile_name');
$wrapper = entity_metadata_wrapper('profile2', $profile);
$wrapper->field_first_name->set(devel_generate_word(mt_rand(6, 12)));

```
> 1 votes

# Answer
I don't know if something changed since '15, but I had to make an adjustment to the accepted answer to get this to work for a specific profile, e.g., presuming `profile2_type` is the machine name of a defined profile:

```
$profile = profile2_load_by_user($account, 'profile2_type');
$wrapper = entity_metadata_wrapper('profile2', $profile->pid);

```

Or, alternatively:

```
$profile = profile2_load_by_user($account);
$wrapper = entity_metadata_wrapper('profile2', $profile['profile2_type']->pid);

```

Note the specific reference to the profile ID.
> 1 votes

# Answer
$profile = profile2\_load\_by\_user($user-\>uid,'profile\_type');this will declare a single object from the logged in user
> 0 votes

---
Tags: 7, users, entities
---


# Question
Title: Need to disable Auto Preview in views for local development in settings.php
Can I add a setting in settings.php to disable Auto Preview in views. I know this can be changed under /views/settings/. But I don't want this configuration added to Git. I only want this change on my local site. Something like this.

```
$config['system??']['foo']['bar'] = FALSE;

```

I unchecked 'Automatically update preview on changes' in Views settings and exported the changes. The result is that it updated 'views.settings' Below is part of views.settings.yml

```
     ui:
      show:
        additional_queries: false
        advanced_column: true
        master_display: true
        performance_statistics: false
        preview_information: true
        sql_query:
          enabled: true
          where: below
        display_embed: false
      always_live_preview: false
      exposed_filter_any_label: old_any

```

The setting may look something like this.

```
$config['views.settings']['ui']['always_live_preview'] = FALSE;

```

# Answer
> 1 votes
This should do it, make sure you clear cache:

```
$config['views.settings']['ui']['always_live_preview'] = 'false';

```

---
Tags: views, 8
---


title: How to get ip address?

text:
# Question
Title: How to get ip address?
I used the following code:

```
services:
  foo:
    class: Drupal\MYMODULE\Foo
    arguments: ['@request']

```

In MYMODULE/src/Foo.php

```
namespace Drupal\MYMODULE;

use Symfony\Component\HttpFoundation\Request;

class Foo {
  /**
   * @var \Symfony\Component\HttpFoundation\Request
   */
  protected $request;

  /**
   * Constructs a Foo object.
   *
   * @param Symfony\Component\HttpFoundation\Request $request
   *   The request object.
   */
  public function __construct(Request $request) {
    $this->request = $request;
  }

  public function bar() {
    if ($ip == $this->request->getClientIp()) {
      drupal_set_message('ip', t('You may not ban your own IP address.'));
    }
  }

}

```

but this gives me error:

> Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException' with message 'The service "foo" has a dependency on a non-existent service "request".

# Answer
Following code worked for me:

```
use Symfony\Component\HttpFoundation;
$ip_address = Drupal::request()->getClientIp();

```
> 2 votes

# Answer
According to Get the user IP address and Symfony HttpFoundation you can get visitor IP by

first add `use Symfony\Component\HttpFoundation;` then

```
 \Drupal::request()->getClientIp()

```
> 21 votes

# Answer
The correct way to do this is via service injection. This way your class is unit testable.

In your `mymodule.services.yml` file:

```
services:
  foo:
    class: Drupal\MYMODULE\Foo
    arguments: ['@request_stack']

```

In your class:

```
namespace Drupal\MYMODULE;

use Symfony\Component\HttpFoundation\RequestStack;

class Foo {
  /**
   * The current request
   *
   * @var \Symfony\Component\HttpFoundation\Request
   */
  protected $request;

  /**
   * Constructs a Foo object.
   *
   * @param Symfony\Component\HttpFoundation\RequestStack $request_stack
   *   The request stack object.
   */
  public function __construct(RequestStack $request_stack) {
    $this->request = $request_stack->getCurrentRequest();
  }

  public function bar() {
    $ip = $this->request->getClientIp();

    // Do something with $ip, just return it back as an example.
    return $ip;
  }

}

```

In your test file:

```
namespace Drupal\Tests\MYMODULE\Unit;

use Drupal\MYMODULE\Foo;
use Drupal\Tests\UnitTestCase;
use Prophecy\Argument;

class FooTest extends UnitTestCase {

  public function testBar() {
    $request = $this->prophesize('\Symfony\Component\HttpFoundation\Request');
    $request->getClientIp()->willReturn('123.123.123.123');
    $request = $request->reveal();

    $request_stack = $this->prophesize('\Symfony\Component\HttpFoundation\RequestStack');
    $request_stack->getCurrentRequest()->willReturn($request);
    $request_stack = $request_stack->reveal();

    $foo = new Foo($request_stack);

    $this->assertEquals($foo->bar(), '123.123.123.123');
  }
}

```
> 14 votes

# Answer
What does the error you received tell you? It tells you that the service `request` does not exist. You can look/discover requests loaded by core reading the core.services.yml file, and discover something similar, a service called `request_stack`.

The `request_stack` service provides Symfony\Component\HttpFoundation\RequestStack with which you can get the current request. The static \Drupal::request is an example implementation of getting the current request.

```
  public function __construct(RequestStack $requestStack) {
    $this->request = $requestStack->getCurrentRequest();
  }

  public function bar() {
    if ($ip == $this->request->getClientIp()) {
      drupal_set_message('ip', t('You may not ban your own IP address.'));
    }
  }

```
> 3 votes

# Answer
If you want to show the ip in twig:

Suppose you want to get the ip in the page.html.twig file.

in your

**YOURTHEME.theme**

you can try

```
use Symfony\Component\HttpFoundation;

function YOURTHEME_preprocess_page(&$variables) {
  $variables['page']['ip'] = \Drupal::request()->getClientIp();

}

```

in your template

**page.html.twig**

you can try:

```
{{ page.ip }}

```
> 0 votes

# Answer
I make the following module for get ip address of visitors

create following route custom\_location/custom\_location.info.yml and following info

```
name: Custom Location
description: Custom Location.
package: Custom
type: module
version: 1.0
core: 8.x

```

custom\_location/custom\_location.links.menu.yml

```
location.admin:
  title: 'Location module settings'
  description: 'location'
  parent: system.admin_config_development
  route_name: location.content
  weight: 100

```

custom\_location/custom\_location.routing.yml

```
location.content:
  path: '/location'
  defaults:
    _controller: '\Drupal\custom_location\Controller\CustomLocation::content'
    _title: 'Ip Table'
  requirements:
    _permission: 'access content'

```

in the route custom\_location/src/Controller/CustomLocation.php

```
<?php
/**
 * @file
 * Contains \Drupal\custom_location\Controller\CustomLocation.
 */
namespace Drupal\custom_location\Controller;
use Symfony\Component\HttpFoundation;
use Symfony\Component\HttpFoundation\RequestStack;

class CustomLocation {
  public function content() {
    $ip_address = \Drupal::request()->getClientIp();
    $html = $ip_address;
    return array(
      '#type' => 'markup',
      '#markup' => $html,
    );
  }
}

```

and visit in your path your location in /location and ready appear the ip
> 0 votes

---
Tags: 8, symfony-services
---


# Question
Title: Is there a way to clear the cache without dropping tables?
I am new to Drupal and realized that when we clear cache in Drupal 'drush cr'. It executes drop db commands.

This is a very big security issue in our company because granting drop privileges to a mysql user on a production server would be dangerous

What would be an alternate solution?

```
  In Connection.php line 686:
  SQLSTATE[42000]: Syntax error or access violation: 1142 DROP command denied to user 'xxxxx'@'100.100.100.100' for table 'webprofiler': TRUNCATE {webprofiler}; Array()

  In Statement.php line 59:
  SQLSTATE[42000]: Syntax error or access violation: 1142 DROP command denied to user 'xxxxx'@'100.100.100.100' for table 'webprofiler'

```

**Correction**

drush cr is **not** dropping tables. MySQL Truncate requires the DROP privilege as of MySQL 5.1.16. (Before 5.1.16, it requires the DELETE privilege). http://dev.mysql.com/doc/refman/5.1/en/truncate-table.htm

So this means when drush cr is run you need a user with drop privileges.

# Answer
> 3 votes
As Kevin correctly points out in the comments, the cache clear is issuing a `TRUNCATE` command rather than `DROP`, but `TRUNCATE` does require the `DROP` permission.

If you look at the manual installation method in the install guide, you'll see that `DROP` is one of the permissions that is granted as part of the setup process:

```
GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, INDEX, ALTER, CREATE TEMPORARY TABLES ON databasename.* TO 'username'@'localhost' IDENTIFIED BY 'password';

```

That's followed shortly after by:

> **Note:** Unless the database user/host combination for your Drupal installation has all of the privileges listed above (except possibly CREATE TEMPORARY TABLES, which is currently only used by Drupal core automated tests and some contributed modules), you will not be able to install or run Drupal.

So `DROP` is simply a required permission for Drupal to work.

---
Tags: drush
---


# Question
Title: How do I theme user reset password page?
How I can **template the user reset password page** when I receive the reset password token based link?

**/user/reset/2289/1545342420/zrmQkJAN9whwgu2xbKCW0KbIKigx7AsUgSo88UKr1c4**

# Answer
Wooha! I found the answer myself. These are the template file names which can be overridden to theme the pages.

**page--user--reset.tpl.php** \- To theme the reset password page when you will receive this of reset password URL in the email. /user/reset/2289/1545342420/zrmQkJAN9whwgu2xbKCW0KbIKigx7AsUgSo88UKr1c4

**page--user--login.tpl.php** \- To reset the user login page.

**page--user--pass.tpl.php** \- To theme the user password page when user enters the email address to recover the password.

See this for more information as well. https://www.drupal.org/node/350634
> 3 votes

---
Tags: theming
---


# Question
Title: Instantiate Controller with Interface not concrete class
As background, I am rebuilding some old code and want to wrap all the curl based requests in an interface (HttpRequestInterface) so I can swap that out later without having to write all the api calls right now.

I am trying to pass the HttpRequestInterface into controller, but it keeps saying \`

> TypeError: Argument 1 passed to Drupal\my\_api\Controller\MyController::\__construct() must be an instance of Drupal\my\_api\Controller\HttpRequestInterface, instance of Drupal\my\_api\Services\HttpRequest\CurlRequest given

I am new to Drupal from the .Net world and love how this functionality is out of the box and it seems like I am following the examples and code I find in core, but obviously I am missing something.

\***One thing that sticks out is that this error message has the wrong namespace for HttpRequestInterface.

Below are the relevant files, I have only included what I think is pertinent to the issue, more can be made available.

Controller:

```
<?php

namespace Drupal\my_api\Controller;

use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Response;
use Drupal\my_api\Controller\BaseApiController;

/**
 * Controller routines for Api routes.
 */
class RallyBoundController extends BaseApiController {

```

\`BaseController:

```
namespace Drupal\my_api\Controller;

use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Controller\ControllerBase;
use Drupal\my_api\Services\HttpRequest\HttpRequestInterace;

/**
 * BaseApiController abstracts away common api concerns.
 */
abstract class BaseApiController extends ControllerBase {
  protected $httpService;

  /**
   * Contructor requires HttpRequest Service.
   *
   * @param HttpRequestInterface $httpService
   *   Implementation of HttpRequestInterface defined in services.yml.
   */
  public function __construct(HttpRequestInterface $httpService) {
    $this->httpService = $httpService;
  }

  /**
   * Get the HttpRequest implemention as interface so we can swap out as needed.
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('my_api.httprequest')
    );
  }

```

Service.yml:

```
services:
  my_api.httprequest:
    class: Drupal\my_api\Services\HttpRequest\CurlRequest

```

HttpRequestInterface:

```
namespace Drupal\my_api\Services\HttpRequest;

/**
 * HttpRequestInterace defines interface for making Http GET Requests.
 */
interface HttpRequestInterface {

```

CurlRequest:

```
namespace Drupal\my_api\Services\HttpRequest;

use Drupal\my_api\Services\HttpRequest\HttpRequestInterface;

/**
 * HttpRequest Implementation of HttpRequestInterface using CURL.
 */
class CurlRequest implements HttpRequestInterface {

```

Thanks for the help.

# Answer
> 1 votes
In the BaseController file, you have a typo in the interface classname. Fix that and clear the cache. Your module namespace seems to be inconsistent too. Your custom classes should be namespaces under the same module name they are defined in.

`use Drupal\my_api\Services\HttpRequest\HttpRequestInterace;`

to

`use Drupal\my_api\Services\HttpRequest\HttpRequestInterface;`

PHP can’t figure out where the class is due to the typo, and expects it to be defined locally in the Controller class file, hence why your error message lists an incorrect namespace to the interface.

---
Tags: 8, page-controller, dependency-injection, symfony-services
---


# Question
Title: How do I enable an onclick event in a link on a form?
I am using the following code.

```
 $form['test'] = array(
        '#type' => 'link',
        '#href' => "javascript:;",
        '#title' => t('Show'),
        '#attributes' => array(
            'onclick' => "show_this();",
            'onsubmit' => 'return false',
        ),
        '#id' => 'myid',
  );

```

Its output is the following.

```
<a href="/javascript%3A%3B" onclick="show_this();" onsubmit="return false" id="myid">Show</a>

```

The *onclick* event is working properly. I want to disable href.

How can I achieve this?

# Answer
> 1 votes
You don't need the `#href` to prevent the event.

```
$form['test'] = [
  '#type' => 'link',
  '#href' => '#',
  '#title' => t('Show'),
  '#attributes' => [
    'onclick' => "alert('hello');return false",
  ],
  '#id' => 'myid',
];

```

In the above example, I removed the `#href` and the `onsubmit` handler and added `return false` after the `alert()` function in the `onclick` handler.
I don't know what you're trying to achieve in your code, but the above example is working for me.

---

UPDATE: I update the `#href` in my answer.

---
Tags: 7, forms, javascript
---


# Question
Title: Edit "Read more" and "Add new comment" links in teaser
I'd like to add a couple classes to the "Read more" and "Add new comment" links in my article teasers in Drupal 8.

I'd do this in Drupal 7 by doing something like this in my theme file.

```
function mytheme_preprocess_node(&$variables) {
  $variables['content']['links']['node']['#links']['node-readmore']['attributes']['class'][] = 'btn btn-primary';
  $variables['content']['links']['node']['#links']['comment-add']['attributes']['class'][] = 'btn btn-primary';
}

```

But this doesn't work in Drupal 8. I dumped the contents of `$variables['content']['links']` and all I got was this:

```
$variables['...']['...'] array(2)
    '#lazy_builder' => array(2)
        string(40) "Drupal\node\NodeViewBuilder::renderLinks"
        array(4)
            string(1) "4"
            string(6) "teaser"
            string(2) "en"
            boolFALSE
    '#weight' => integer100

```

So how would I go about adding classes to these links in Drupal 8?

# Answer
After playing around with kint and the preprocessor function in mradcliffe's answer, here's what I used in my theme file to get this working:

```
function mytheme_preprocess_links(&$variables) {
    if ( isset($variables['links']['node-readmore']['attributes']) && method_exists($variables['links']['node-readmore']['attributes'], 'addClass') ) {
        $variables['links']['node-readmore']['attributes']->addClass('btn btn-primary');
    }
    if ( isset($variables['links']['comment-add']['attributes']) && method_exists($variables['links']['comment-add']['attributes'], 'addClass') ) {
        $variables['links']['comment-add']['attributes']->addClass('btn btn-info');
    }
}

```

Not pretty, but it works. If anyone has a better optimized solution, let me know, thanks!

## Update

I noticed my answer above actually applied the classes to the `<li>` that surrounds the link instead of the `<a>` tag itself. Upon playing with it a little more, I figured out it needs to be done like this to actually add the classes to the `<a>` tag:

```
function cabootstrap_preprocess_links(&$variables) {
    $variables['links']['node-readmore']['link']['#options']['attributes']['class'][] = 'btn btn-primary';
    $variables['links']['comment-add']['link']['#options']['attributes']['class'][] = 'btn btn-info';
}

```
> 4 votes

# Answer
You can do this in a couple of different ways. By looking up the Drupal\node\NodeViewBuilder::renderLinks method, you can see how it works.

### 1. Implement hook\_node\_links\_alter()

This should work for a module.

```
function mymodule_node_links_alter(array &$links, NodeInterface $entity, array &$context) {
  $links['node']['#links']['node-readmore']['#attributes']['class'][] = 'btn btn-primary';
}

```

### 2. Implement template\_preprocess\_links()

And I think this should work for the theme...

```
function mytheme_preprocess_links(&$variables) {
  // some logic enclosing this block
  $variables['node']['#links']['node-readmore']['#attributes']['class'][] = 'btn btn-primary';
}

```
> 4 votes

# Answer
If you want to modify the text of the link, use the following snippet.

```
function theme_preprocess_links(&$variables) {
  if (isset($variables['links']['node-readmore'])) {
    $variables['links']['node-readmore']['link']['#title'] = t('LEARN MORE');
  }
}

```
> 0 votes

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


# Question
Title: Fatal error: Maximum execution time of 240 seconds exceeded in sites/all/modules/memcache/memcache.inc on line 353
I am using multidomain site .
After adding a new domain record, I was asked as follows: Content access permission needs to be rebuilt on this page.

When I clicked on Rebuild Permissions button, the progress bar started the batch operation of rebuilding but in the midway it stopped and gave an error given below

> Rebuilding Content Access Permissions
>
> An error has occurred. Please continue to the error page An HTTP error 0 occurred. /index.php?q=batch&id=433&op=do

I then searched an found an issue similar to the above in the link given below

```
https://www.drupal.org/node/399572

```

I found many solutions from above like :

1. Run rebuild permission via cron (did not try)
2. change theme and move to older jquery version (did not try as its live site) I checked the settings for jquery update and had "minified" instead of "none", once set to the correct setting, it worked within seconds.

I was using jQuery update module with jQuery 1.4. This causes the batch to not update.

3. (did not try) To fix it, you have to prevent newer jQuery from loading when the URI contains "batch".

```
<?php
function node_access_rebuild($batch_mode = FALSE) {
  db_query("DELETE FROM {node_access}");
  // Only recalculate if the site is using a node_access module.
  if (count(module_implements('node_grants'))) {
//      if ($batch_mode) {
      if (FALSE) {
      $batch = array(
        'title' => t('Rebuilding content access permissions'),
        'operations' => array(
          array('_node_access_rebuild_batch_operation', array()),
        ),
        'finished' => '_node_access_rebuild_batch_finished'
      );
      batch_set($batch);
    }
?>

```

Not sure why this is happening to me, but I've found that I can just force node\_access\_rebuild() to not use batch mode by changing line 2314 of node.module from:
4. In node.module this piece of code, is setting time limit to 240 secs which might be still low than ur php.ini. You can try increasing set\_time\_limit arg to 1000 and then changing it back to 240 to keep code consistent.

```
 if (!ini_get('safe_mode')) {
        set_time_limit(240);
      }
      $result = db_query("SELECT nid FROM {node}");
      while ($node = db_fetch_object($result)) {
        $loaded_node = node_load($node->nid, NULL, TRUE);
        // To preserve database integrity, only aquire grants if the node
        // loads successfully.
        if (!empty($loaded_node)) {
          node_access_acquire_grants($loaded_node);
        }
      }
    }
  }

```

What I tried was increased the max\_execution\_time from 30 to 1000? But still it did not solve the problem Then finally I tried rebuilding permissions via drush

using drush command

```
drush php-eval 'node_access_rebuild();'

```

But that gave me the following error as shown below

```
PHP Fatal error:  Maximum execution time of 240 seconds exceeded in
sites/all/modules/me                                                                                mcache/memcache.inc on line 353

```

Does the above error means this is something to with memcache and will it be worth trying to disable the memcache and then perform rebuilding node access?

http://example.com/index.php?q=admin/content/node-settings/rebuild

# Answer
Set `max_execution_time = 0` in php.ini to allow unlimited execution times, and disable the `set_time_limit()` PHP function (also via php.ini) to prevent Drupal from self-limiting its execution time back to 240 s. Otherwise, you would have to find *all* the places where Drupal calls `set_time_limit()` and increase the values there or set them to zero.

(In Drupal 7, this got simpler through the new `drupal_set_time_limit()` wrapper function, which will not call `set_time_limit()` at all if the current time limit is `0` (unlimited). To be exact, this works since Drupal 7.40, and before was prevented by issue #2233929.)
> 0 votes

# Answer
You can simply add sites/default/settings.php.

> ```
> ini_set('max_execution_time', 0);
>
> ```
> 0 votes

---
Tags: 6, users, caching
---


# Question
Title: How do I allow regular non-admin users to view other users' emails?
Email is now an included field in core, but the stock email for users seems to be set to private; only users with administrator privileges or the user themselves can see.

I'd like to allow other users to see this basic field, without having to create yet another email field where someone has to copy the information over from the other other simply for the ability for it to be visible.

This should be a fairly easy/common practice, but I can't find anything yet.

How do I allow regular non-admin users to view other users' emails?

# Answer
I had a similar use case. Here's another solution: I added a new email field to users' profiles, and in a custom module (I did this is Drupal v8.1), use `hook_user_presave`See Drupal Api:

`function MYMODULE_user_presave(User $user){
 $user->set('field_profile_email', $user->getEmail());
}`

Then you can use this new field in Views, for example, in a department contact list, as was mentioned in a comment to the question. You could use Field Permissions to further enhance this as well.

This does have the downside of creating a second field, but the function avoids having to manually copy it, and it's now available anywhere.
> 2 votes

# Answer
One route you can take is to allow users the *View user information* permission and display this information on the user profile page.

To do so, override **user.html.twig** in your theme (copy it from **core/modules/user/templates/user.html.twig** to your theme's template directory) then inject the email into the template via `hook_preprocess_user()` in your **mytheme.theme** file:

```
/**
 * Implements hook_preprocess_user()
 */
function mytheme_preprocess_user(&$variables) {
  $variables['mail'] = $variables['user']->getEmail();
}

```

In this example, you'll be able to user `{{ mail }}` to insert the email variable into your user profile template.
> 7 votes

# Answer
There is a D8 Vore feature request to add a permission to see other users' mail address: Add new permission to view user email field \[#2799049\] \\| Drupal.org
> 0 votes

---
Tags: 8, users, emails
---


# Question
Title: How can I set the template to use for a view page display?
I created a view for my content, where fields are displayed as a page. Scanning the source code, I noticed it uses the *html--default--2.html.twig* template.

I created a new custom template. how can I set that template for all the view pages, instead of the default template? I need to edit the whole page, including header and footer.

Notice that I've read this and this about custom templates for view. I've tried to rename my custom template *views-view--page.html.twig*, and put it in my template folder, and also in /core/modules/views/templates, flushed cache, but nothing happens. My view page is still using the default template.

# Answer
if you want to add new page template only for views:

1. Implement hook\_theme\_suggestions\_page\_alter like the following:

```

/**
 * Implements hook_theme_suggestions_page_alter().
 */
function mymodule_theme_suggestions_page_alter(&$suggestions, $variables) {
  //- Get the current route name.
  $route_name = \Drupal::routeMatch()->getRouteName();
  //- Check if the current route is a view.
  if (strpos($route_name, 'view') === 0) {
    //- Add suggestion to page when its a view page.
    $suggestions[] = 'page_views_view';
  }
}

```

Now in your views page you will have suggestions something like:

```
<!-- FILE NAME SUGGESTIONS:
   x page-views-view.html.twig
   * page--en.html.twig
   * page--list-page.html.twig
   * page.html.twig
-->

```
1. Now implement hook\_theme like the following:

```

/**
 2. Implements hook_theme().
 */
function mymodule_theme($existing, $type, $theme, $path) {
  return [
    'page_views_view' => [
      'base hook' => 'page',
    ],
  ];
}

```
3. Then Create `page-views-view.html.twig` template inside `templates` folder in your module root folder.
4. Flush all cache.
> 0 votes

---
Tags: views, theming
---


# Question
Title: How do I set a dynamic variable in the menu links yml file for route_parameters?
I'd like to create a menu item that has a dynamic variable in it, specifically the user's ID.

This is the content of the *example.routing.yml* file.

```
example.test:
  path: '/user/{user}/example'
  defaults:
    _controller: '\Drupal\example\Controller\ExampleController::test'
    _title: 'Test'
  requirements:
    _permission: 'access content'
    user: ^[0-9]+

```

This is the content of the *example.links.menu.yml* file.

```
example.testlink:
  title: Test Link
  parent: example.parent
  description: 'Test Link'
  route_name: example.test
  weight: 3
  route_parameters: {user: 5}

```

*5* is the user ID. I'd like to pull it from the logged-in user.

Is this possible?

# Answer
It isn't possible to put dynamic variables into a menu.links.yml file. However, you can create a menu links class and set route parameters in there. You need to specify the class in the yaml file.

```
my_dynamic_link:
  route: my_route
  class: Drupal\my_module\Plugin\Menu

```

You can also include the normal menu link stuff like the menu\_name in the yaml file.

The class extends MenuLinkBase and requires the getTitle(), getDescription(), and updateLink() methods, but the method we're interested in is the getRouteParameters() method. Simply return an array with your route parameters and you're golden.

```
public function getRouteParameters() {
  return [
    'user' => $current_user->id(),
  ];
}

```
> 3 votes

---
Tags: 8
---


title: How can I fix this update issue?

text:
# Question
Title: How can I fix this update issue?
I have updated a Drupal site from 8.5.3 to 8.6.3 and got the following error related to the webform module. Can anyone help me fix this?

> webform module
> Update #8108
>
> Failed: Drupal\Core\Database\DatabaseExceptionWrapper: SQLSTATE\[42S22\]: Column not found: 1054 Unknown column 'block\_content\_field\_data.reusable' in 'where clause': SELECT base\_table.revision\_id AS revision\_id, base\_table.id AS id FROM {block\_content} base\_table INNER JOIN {block\_content\_field\_data} block\_content\_field\_data ON block\_content\_field\_data.id = base\_table.id WHERE (block\_content\_field\_data.reusable IN (:db\_condition\_placeholder\_0)) AND (block\_content\_field\_data.default\_langcode IN (:db\_condition\_placeholder\_1)); Array ( \[:db\_condition\_placeholder\_0\] =\> 1 \[:db\_condition\_placeholder\_1\] =\> 1 ) in Drupal\Core\Entity\EntityStorageBase-\>loadByProperties()(line 541 of C:\xampp\htdocs\html86-13nov\core\lib\Drupal\Core\Entity\EntityStorageBase.php).

# Answer
You need to apply the database updates. If you have Drush, just run `drush @YOUR_ENV_ALIAS updb`. Otherwise, log in into your website and go through the update process from https://example.com/update.php. (Replace *example.com* with the domain name used from the site.)
> 0 votes

---
Tags: 8, updating
---


# Question
Title: Translation of a element['#object'] rendered field
I have some fields in which I rendered additional fields from a nested term via element\['#object'\]:

e.g. {{ element\['#object'\].field\_country.entity.name.value }}

Unfortunately, this fields do not translate inside the node view although the node and the nested term itself is translated.

How can I make them display with their translation?

# Answer
Use getTranslation(), see How to load translated entity values in Twig for SEO purpose?.

In your case you can try something like this:

```
{% if element['#object'].field_country.entity.hastranslation(element['#object'].langcode.value) %}
  {{ element['#object'].field_country.entity.translation(element['#object'].langcode.value).name.value }}
{% else %}
  {{ element['#object'].field_country.entity.name.value }}
{% endif %}

```
> 1 votes

---
Tags: theming
---


title: MetaTag with JSON API won't serialize

text:
# Question
Title: MetaTag with JSON API won't serialize
I'm attempting to get MetaTag info for a decoupled site but the JSON API is not converting the object to JSON correctly. I'm seeing other fields show up fine - the issue is isolated to the MetaTags.

The output appears like this:

```
field_meta_tags: "a:2:{s:5:"title";s:10:"Test Title";s:11:"description";s:21:"Test Body Description";}",

```

From what I can tell, s:5 represents an string of 5 characters ("title"), s10 represents 10 characters ("Test Title"), etc etc. Has anyone seen this before?

Drupal 8 Metatag version: '8.x-1.5' JSON API version: '8.x-1.16'

# Answer
In fact, the metatag field IS serialized. As stated by Monkeybrain, the result you get as field value is a serialized PHP array.

This is due to the nature of the metatag field, which internally stores its value as a string (serialized PHP array). By using the JSON API module alone, you'll get this value only.

If you need the serialized PHP array to be an unserialized JSON object, you will have to do some custom programming.

Either implement an own REST API endpoint, or - probably easier to do - use the JSON API extras module. It introduces an additional resource field enhancer plugin type to process the values of JSON API entity fields. So you can create an own custom module providing a ResourceFieldEnhancer plugin for the metatags field, which could do your desired unserialization.

Bear in mind, that the value saved within the metatag field(s) does not contain entity defaults. If these are required, you should also use the Metatag module's `metatag.manager` service to additionally fetch this information.
> 0 votes

# Answer
> So you can create an own custom module providing a ResourceFieldEnhancer plugin for the metatags field, which could do your desired unserialization.

This won't work as entities that don't have customized overrides of the default metatags do have a value NULL and thus they're not processed by an enhancer at all.

The patch here works nicely and adds an unserialized output in the jsonapi resource: https://www.drupal.org/project/metatag/issues/2945817

The output the patch produces in the resource can be found in the attribute key **metatag\_normalized**.
> 0 votes

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


# Question
Title: Language switcher links are hidden for anonymous users
I'm trying to add a language switcher to a Drupal 8 site menu (it's switching between English and Spanish). I have the links working when logged in as admin but they're not shown for anonymous users, even though the language switcher block displays fine, as well as adding a language switcher through twig. However, I'd really like to get this working and be able to add it to menus through a custom module.

As an anonymous user I am able to view the translated content (by clicking the Default Drupal language switcher options) but these links that are created are not rendered.

Here's my code for the custom module:

MYMODULE.links.menu.yml

```
MYMODULE.switch:
  class: Drupal\MYMODULE\Plugin\Menu\MenuLanguageLink
  menu_name: MENUNAME
  route_name: '<current>'
  options:
    attributes:
      hreflang: 'en'
MYMODULE.switch_2:
  class: Drupal\MYMODULE\Plugin\Menu\MenuLanguageLink
  menu_name: MENU2NAME
  route_name: '<current>'
  options:
    attributes:
      hreflang: 'es'

```

/src/Plugin/Menu/MenuLanguageLink.php:

```
<?php
/**
 * @file
 * Contains \Drupal\MYMODULE\Plugin\Menu\LanguageSwitchController.
 */
namespace Drupal\MYMODULE\Plugin\Menu;

use Drupal\Core\Menu\MenuLinkBase;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

class MenuLanguageLink extends MenuLinkBase implements ContainerFactoryPluginInterface {

  /** @var array Available languages */
  protected $languages = [];

  /**
   * {@inheritdoc}
   */
  public function __construct(
    array $configuration,
    $plugin_id,
    $plugin_definition,
    LanguageManagerInterface $language_manager
  ) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->languages = $language_manager->getLanguages();
  }

  /**
   * Dependency injection.
   */
  public static function create(
    ContainerInterface $container,
    array $configuration,
    $plugin_id,
    $plugin_definition
  ) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('language_manager')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function updateLink(array $new_definition_values, $persist) {
    return $this->pluginDefinition;
  }

  /**
   * {@inheritdoc}
   */
  public function getOptions() {
    $options = parent::getOptions();
    $langcode = $options['attributes']['hreflang'];

    if (isset($this->languages[$langcode])) {
      $options += ['language' => $this->languages[$langcode]];
    }

    return $options;
  }

  /**
   * {@inheritdoc}
   */
  public function getTitle() {
    $langcode = $this->getOptions()['attributes']['hreflang'];
    if ($langcode == 'es') {
      return 'Español';
    } else {
      return $this->languages[$langcode]->getName();
    }
  }

  /**
   * {@inheritdoc}
   */
  public function getDescription() {
    return $this->t('Switch Language');
  }

}

```

# Answer
> 2 votes
After installing your module, I can confirm the behavior that you're seeing.

When I change the route to `<front>` I am able to see the links as anonymous.

What I know is that the menu system automatically checks if the user has access or permission before it displays the links.

So my first thought is there must be a Core bug with this `<current>` route.

When I check /core/modules/system/**system.routing.yml** all I see is:

```
'<current>':
  path: '<current>'

```

Which is interesting that this route doesn't have an access nor a permission key.

In /admin/people/permissions if I check this permission:

> Link to any page
>
> *Warning: Give to trusted roles only; this permission has security implications. This allows to bypass access checking when linking to internal paths.*

I can see the links as anonymous, but obivously we do not want to this.

---

When I try to add `<current>` via the UI, I cannot; even though, `<front>` is acceptable.

Therefore, my best educated guess, seems to me that the `<current>` route is not designed to be used in Menu links because it doesn't have an access key nor permission key. Also, this might explain why the language switcher is a block and not a menu link.

---

However, there is work around for this if you pro-grammatically print the menu and not perform an access check, but there is a caveat. You would have to make sure there is no link in this menu that anonymous is not suppose to see.

As per code provided in Menu system, "Rendering" section, comment out the access check part.

Example:

```
    $menu_tree = \Drupal::menuTree();
    $menu_name = 'MENUNAME';

    // Build the typical default set of menu tree parameters.
    $parameters = $menu_tree
      ->getCurrentRouteMenuTreeParameters($menu_name);

    // Load the tree based on this set of parameters.
    $tree = $menu_tree
      ->load($menu_name, $parameters);

    // Transform the tree using the manipulators you want.
    $manipulators = array(
//    // Only show links that are accessible for the current user.
//    array(
//      'callable' => 'menu.default_tree_manipulators:checkAccess',
//    ),
      // Use the default sorting of menu links.
      array(
        'callable' => 'menu.default_tree_manipulators:generateIndexAndSort',
      ),
    );
    $tree = $menu_tree
      ->transform($tree, $manipulators);

    // Finally, build a renderable array from the transformed tree.
    $menu = $menu_tree
      ->build($tree);
    $menu_html = drupal_render($menu);

    print $menu_html; // print the menu

```

If the above does not suffice, because of the caveat, you might want to look into

> Potentially write a custom menu tree manipulator, see \Drupal\Core\Menu\DefaultMenuLinkTreeManipulators for examples. This is only necessary if you want to do things like adding extra metadata to rendered links to display icons next to them.
>
> source: Menu System

I believe here you will be able to target specifically the language menu links and make Drupal skip the access check only on those specific language links which would be the best solution.

---
Tags: i18n-l10n
---


# Question
Title: How can check if a field is empty in a node template?
I am using Drupal 8. I have a paragraphs field (field type: paragraphs of reference revisions) in node template, I tried lots of ways to check if the field is empty (purpose is to show the field only it has a value).

```
<code>
{# Below codes in node.html.twig #}
{# Below codes NOT work #}
  {% if content.field_notes.0 is empty %}
    This field is empty-1.
  {% endif %}

  {% if content.field_notes[0] is empty %}
    This field is empty-2.
  {% endif %}

  {# Enable module:twig field value #}
  {% if content.field_notes|field_value is empty %}
    This field is empty-3.
  {% endif %}

  {% if node.field_notes.isempty %}
    This field is empty-4.
  {% endif %}

  {% if node.field_notes.value is empty %}
    This field is empty-5.
  {% endif %}
</code>

```

How can check if a paragraphs field is empty in node template in Drupal 8?

**UPDATE:** Codes tested and result below, the way NOT work for paragraphs but work for some other field types.

`{% set count_field_element_1 = node.field_paragraphs|length %}
 {{ count_field_element_1 }}
 {# when field has or no value: count_field_element_1 = 2 #}
 {# paragraphs type contains two field type: image and text plain long #}`

`{% set count_field_element_2 = node.field_image|length %}
 {{ count_field_element_2 }}
 {# when field has value: count_field_element_2 = 1; #}
 {# when field has no value: count_field_element_2 = 0; #}`

`{% set count_field_element_3 = node.field_text_plain_long|length %}
 {{ count_field_element_3 }}
 {# when field has value: count_field_element_3 = 1; #}
 {# when field has no value: count_field_element_3 = 0; #}`

Maybe my question is not very clear, let me explain more as below: The purpose of this question is to check if paragraphs field (not other field types) has a value. When a field value is input and saved, node page will show the field and its value; when no field value is input and saved, node page will NOT show the field (including the div element).

`{% set count_field_element = node.field_paragraphs|length %}
 {{ count_field_element }}`

**count\_field\_element is 1 for below:**

**count\_field\_element is 0 for below(removing all form items of paragraphs in node form):**

In short, up till now, I still NOT figure out a way to check if a paragraphs field has a value, node page will show paragraphs field empty only when removing all form items of paragraphs in node form.

# Answer
> 3 votes
Check on `node.field_notes` something like

```

 {% set count_paragraph_element = node.field_notes | length %}
  {% if count_paragraph_element == 0 %}
      Empty
  {% else %}
      Not empty
  {% endif %}

```

**Update**
if you want to check if `text plain long` field has empty value try this.
I assume that your field machine name is `field_text`:

```

{% for item in node.field_notes %}
      {% if item.entity.field_text.value is empty %}
        text value is empty
      {% else %}
        text value not empty
      {% endif %}
{% endfor %}

```

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


# Question
Title: Adding a filter to a view "or" remove results?
I've got a view that is trying to show three different content types (Lesson, Drill, Exercise), each with three different flags(Lesson Flag, Drill Flag, Exercise Flag), each of those flags have 3 fields (Review Date, Review Date, Lesson Status). I only want to display items that have a flag with REVIEW date \<= today, OR learning status of Incomplete. But when I add the OR condition that the flags learning status = incomplete, all of the results of the other two content types are removed. (IE, before adding the filter I have 7 items, after adding the filter the view only shows one item that wasn't there before)

This seems to defy my understanding of how the "or" condition works, and I'm curious why this would happen.

Here's a picture with the filters I have set up:

Is there something I'm not understanding about how the OR condition works? Or an existing bugs in views 7x.3x that causes them to behave badly?

# Answer
> 1 votes
I figured this out. In order to prevent this behavior, I had to check "reduce duplicates" in the filter, as well as remove some "required relationships.

---
Tags: 7, views
---


# Question
Title: How can check if current user is node author in node template
I am using Drupal 8. I would like to check if user (anonymous or logged user) is node author in node.html.twig, like below:

```
{# node.html.twig #}
  {% if is_author %}
    You are node author
  {% else %}
    You are not node author
  {% endif %}

```

Below codes not work:

```
/**
 * Implements hook_preprocess_HOOK().
 */
function MYTHENE_preprocess_node(&$variables) {
  $global $user;
  if ($variables['node']->uid == $user->uid) {
    $variables['is_author'] = TRUE;
  }
  else {
    $variables['is_author'] = FALSE;
  }
}

```

How could I create variable 'is\_author' in node.html.twig?

# Answer
```
/**
 * Implements hook_preprocess_HOOK() for node.html.twig.
 */
function mytheme_preprocess_node(&$variables) {
   $uid = \Drupal::currentUser()->id();
   $author_id = $variables['node']->getOwner()->id();
   if ($author_id == $uid) {
     $variables['is_author'] = TRUE;
   }
   else {
     $variables['is_author'] = FALSE;
   }
}

```
> 1 votes

# Answer
The problem with your approach and Jimmy's answer is, that in production with Drupal's default caching this won't work. The snippet that you placed in the preprocess function simply gets cached after the first execution until you manually rebuild Drupal's cache.

To reproduce it simply create two new users, open two anonymous browser windows and in each log in as one of the users. With the first user create a node and rebuild the cache with `drush cr`. "You are node author" will be displayed. Fine. But now in the second browser window logged in as the second user visit the node and you will also see "You are node author". Bad. Only after `drush cr` and a refreshed browser window you'll see "You are not node author". Same now when you get back to the first user and refresh the browser window, you'll see "You are not node author". Until you rebuild the cache again.

What you could do now to solve the problem is to provide a render array instead and take control of its cache contexts.

In your node template put:

```
{{ foobar }}

```

And in your theme file put:

```
/**
 * Implements hook_preprocess_HOOK() for node.html.twig.
 */
function MYTHEME_preprocess_node(&$variables) {

  $variables['foobar'] = [
    '#markup' => '',
    '#cache' => [
      'contexts' => [
        // As we need this piece of markup to be user-sensitive
        // we tell Drupal to vary the output by the 'user' cache context.
        'user',
      ],
    ]
  ];

  // The rest of the logic can stay basically the same.
  $uid = \Drupal::currentUser()->id();
  $author_id = $variables['node']->getOwner()->id();
  if ($author_id == $uid) {
    $variables['foobar']['#markup'] = t('You are node author');
  }
  else {
    $variables['foobar']['#markup'] = t('You are not node author');
  }
}

```

For more info see Cacheability of render arrays from where I've taken the sample.

---

Note that with advanced server-side caching (Varnish etc.) this approach still won't work. It then needs to get Ajaxified.
> 1 votes

---
Tags: 8, theming
---


title: How to know "keys" for Entity::create()

text:
# Question
Title: How to know "keys" for Entity::create()
The document says `Entity::create()` takes

> "$values (optional) An array of values to set, keyed by property name"

as an arguement.

I also found snippets like

```
$term = Term::create([
    'name' => $term_name,
    'vid' => $vocabulary_name,
  ]);

```

and they worked.

But how exactly do you know what kind of values can be set in the array?
In the case above, where did people take the keys `'name'` and `'vid'` from?

# Answer
If you look at the of `baseFieldDefinitions` method in class Term:

Here is a list of fields you can set in create Term:

1. `tid` : Term ID
2. `uuid` : The term UUID.
3. `vid`: The vocabulary to which the term is assigned.
4. `langcode` : The term language code.
5. `name` : Name of term.
6. `description` : description of term
7. `weight` : weight of term.
8. `parent` : Term parent.

Example:

```
$term = Term::create([
    'name' => 'term name',
    'vid' => 'tags',
    'status' => 1,
    'tid' => 13,
    'uuid' => 1,
    'langcode' => 'en',
    'description' => 'tags description',
    'weight' => -12,
    //'parent' => parent tid
  ]);
  $term->save();

```
> 1 votes

# Answer
Load an existing term

```
$term = Term::load(1);

```

or create an empty term to get the vocabulary specific bundle fields

```
$term = Term::create([
  'vid' => $vocabulary_name,
]);

```

and dump it as an array:

```
var_dump($term->toArray());

```
> 1 votes

---
Tags: 8, entities
---


# Question
Title: Rule to notify admin by email whenever anyone updates a field in a user profile
I have allowed a certain 'role' to change/edit fields in 'registered' users' fields. I want to receive an email in the admin's inbox detailing these changes using Rules.

I tried and failed!

Any help to achieve this?

i.e.

```
Subject: [user, who changed the field in a registered user's profile] changed [user, whose profile settings have been changed] profile
Body: [changed by]
[user whose profile was changed]
[value of changed filed in profile]
[value changed at]

```

# Answer
> -2 votes
I am giving you the alternate idea instead of using rules,you can use hook\_form\_alter.

```
use Drupal\Core\Database\Database;
use Drupal\Core\Form\FormStateInterface;
 function getCurrentUserRecord()
 {
  $myArray = [];
  $x = db_select('users_field_data','cw')
    ->fields('cw',['name','pass','mail'])
    ->execute()->fetchAll();

  foreach($x as $v){
    $myArray = $v;
  }
  return $myArray;
  }

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

      if($form_id == "user_form")
       {

            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)
{
$records = getCurrentUserRecord();

$field=$form_state->getValues();
$mail = $field[mail];
$name = $field[name];

if($records->name == $name || $records->mail == $mail)  {
    drupal_set_message(t("No changes so far"), 'error');
}
  else{

    $mailManager = \Drupal::service('plugin.manager.mail');
    $module = 'nestle_viewalter';
    $key = 'update_profile';
    $to = 'vikram@sparxitsolutions.com';
    $send = true;
    $result = $mailManager->mail($module, $key, $to,NULL, $send);

    if ($result['result'] !== true) {
        drupal_set_message(t('There was a problem sending your message and it was not sent.'), 'error');
    }
    else {
        drupal_set_message(t('Your message has been sent.'));
    }

    drupal_set_message(t("Send mail"), 'status');
}
}

  function nestle_viewalter_mail($key, &$message, $params) {
 switch ($key) {
 case 'update_profile':
 $message['from'] = \Drupal::currentUser()->getEmail();
 $message['subject'] = t('Profile updated');
 $message['body'][] = 'this is a test mail from the current user as i have updated my profile.';
 break;
 }
 }

```

---
Tags: 8, rules
---


# Question
Title: How to change permissions to a role when a content is set as published
I have been working with Drupal 8 and need help: I have a News content type, and an Editor role type. This Editor role can view/edit/delete his own content. I want that Editor roles can't edit/delete their own content when this content is published by Admin roles.

I have been searched and I found Permissions by fields, Permissions by terms, Groups and Custom Publish options modules, but I can't make this works.

Maybe this can be done with php, but I don't know how.

Please, any help?

# Answer
You could use the following code.

```
use Drupal\Core\Access\AccessResult;
use Drupal\node\NodeInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\user\Entity;

function mymodule_node_access(NodeInterface $node, $op, AccountInterface $account) {
  $type = $node->getType();
  // Is it published?
  $nodeIsPublished = $node->isPublished();
  if ($type == 'news' && $operation != 'view' && $nodeIsPublished == 1) {
    if($account->hasRole('rolename')) {
       return  AccessResult::forbidden();
    }
    else {
      return AccessResult::allowed();
    }
  }
  return AccessResult::neutral();
}

```

Also, the Override Node Options module allows permissions to be set for each field within the *Authoring information* and *Publishing options* fieldsets on the node form.
> 1 votes

---
Tags: users
---


# Question
Title: How to print the Views title in page.tpl.php?
I could print the view with this code in `page.tpl.php`.

```
print $view->display['view_display_name']->display_options['title'];

```

How can I print the Views title ?

# Answer
> 0 votes
You can aptly use this function views\_embed\_view(). This will help you to print out the view, passing arguments.

# Answer
> 0 votes
If I correctly understand your question, you are actually looking for how to define `$view`. That can easily be done with `views_get_view()`. Add `<?php $view=views_get_view('YOUR-VIEW'); ?>` to `page.tpl.php` or predefine the variable with `template_preprocess_page()` in your theme's `template.php` file. You can then print the View's title with your code line.

# Answer
> 0 votes
Add the following code in your template.php

```
function themename_preprocess_page(&$variables) {
  $name = 'view_machine_name';
  $display_id = 'block_1';
  $view = views_get_view($name);
  if(isset($view) && !empty($view)) {
    $head_title = $view->get_title();
    $variables['view_title'] = $head_title;
  }
}

```

add the following variable anywhere in the page.tpl.php file used by your theme.

```
 print $view_title;

```

---
Tags: views, 7
---


title: How do I link a page in a template?

text:
# Question
Title: How do I link a page in a template?
If there is a basic page with the route '/about', how can I link it in a template file?

```
<a href="{{ What goes here? }}"></a>

```

# Answer
> 2 votes
Let assume the page is a node whose ID is 4. You can use the following code, in a template file.

```
<a href="{{ path('entity.node.canonical', {'node': 4}) }}">About us</a>"

```

# Answer
> 1 votes
You can use the path function to call specific routes

```
<a href="{{ path('user.register') }}">My link</a>

```

Or of course, you can do it the old-fashioned way

```
<a href="/about">My link</a>

```

---
Tags: theming
---


# Question
Title: Can't send managed file as mail attachment
I'm working on a form submit in a Drupal 7 project, the form has and upload file field, in my form submit handler I can get the file id, what I want to do is to send and mail which has as attachment the uploaded file.

my form submit function:

```
function my_form_submit($form, &$form_state) {
  $fid = $form_state['values']['document'];
  $file = file_load($fid);
  $params = array(
    'attachment' => $file,
  );
  global $language;
    drupal_mail('my_module', 'key_1', 'my_own_mail@gmail.com', $language, $params);

}

```

hook\_mail implementation:

```
function my_module_mail($key, &$message, $params){
  switch ($key) {
    case 'key_1':
      $message['subject'] = t('my mail subject');
      $message['body'][] = t('Hello this is a test content');
      $message['params']['attachments'][] = $params['attachment'];
  }
}

```

When submitting the form the mail has not been sent and this error is shown:

```
Error : Cannot use object of type stdClass as array in my_module_mail()

```

Anybody has an idea why it doesn't accept object and or how to deal with this in this case. Thanks.

# Answer
> 1 votes
file\_load return file object:

> Loads a single file object from the database.

But `$message['params']['attachments'][]` should be an array.
So just change `$file = file_load($fid);` to `$file = (array)file_load($fid);` in your submit function `my_form_submit` will be like:

```
function my_form_submit($form, &$form_state) {
  $fid = $form_state['values']['document'];
  //file object as an array.
  $file = (array)file_load($fid);
  $params = array(
    'attachment' => $file,
  );
  global $language;
    drupal_mail('my_module', 'key_1', 'my_own_mail@gmail.com', $language, $params);

}

```

**Update**:

to send attachement you need just the `filePath` try with:

```
$params = array(
    'attachments' => array(
      0 => array(
        'filepath' => $file->uri,
      ),
    ),
  );

```

---
Tags: 7, emails
---


title: Get Link value in Media entity

text:
# Question
Title: Get Link value in Media entity
We have a `Media` type called `Documents` that has a `Link` field called `field_link`. We need to obtain the URL (external or internal) from the field so that we can use to wrap block elements inside of a `<a>` tag in our twig templates. All works fine when the link is an external URL, but when linking to an internal page, the following code does not work in our `mymodule_preprocess_media` hook.

**How can I obtain both the internal and external link within the `field_link` field inside of the `mymodule_preprocess_media` hook?**

This is what we have tried, but only works for `external` links.

```
function mymodule_preprocess_media(&$variables) {
  $media_entity = $variables['elements']['#media'];
  $link = $media_entity->get('field_link')->first();

  // This works for external, but not internal
  $link_value = $link->getUrl()->getUri();

  $variables['custom_var'] = [
    'link_value' => $link_value,
  ];
}

```

**`media--document.html.twig`**

```
<a href="{{ custom_var['link_value'] }}">
  <div>{{ name }}</div>
</a>

```

When using `ksm($link->getUrl())`, we find that the `uri` value is `NULL` when the link is internal.

**Goals:**

1. Get the internal link (absolute) using `hook_preprocess_media`
2. Get the external link using `hook_preprocess_media`

# Answer
> 1 votes
Try the following:

```
/**
 * Implements hook_preprocess_media().
 */
function mymodule_preprocess_media(&$variables) {
  $media_entity = $variables['elements']['#media'];
  /**
   * @note: in case your field not multiple, otherwise loop through the field.
   */
  $link = $media_entity->get('field_link')->first();
  if ($link->isExternal()) {
    //- External.
    $link_value = $link->getValue()['uri'];
  }
  else {
    //- internal.
    $link_value = $link->getUrl()->toString();
  }
  $variables['custom_var'] = [
    'link_value' => $link_value,
  ];
}

```

---
Tags: theming, hooks, media
---


# Question
Title: How do I programmatically render a view that has exposed filters?
I can call a view with contextual filters without any problem, but when I add exposed filter value $view-\>setExposedInput to the call, I just does not work, the exposed value is not applied and being ignored. The filter 'price' field is set in the views filters options and i tried both exposing it and not exposing it to visitors without any luck. I call this view from my controller class and I need to pass the arguments to both filters and I do not need exposed form to be displayed to the user.

```
$view = Views::getView($view_id);
if (is_object($view)) {
  $filters = [
       'price' => 500, //my exposed filter value
     ];
  $view->setExposedInput($filters);
  $view->setArguments($args);
  $view->setDisplay($display_id);
  $view->preExecute();
  $view->execute();
  $view->buildRenderable($display_id, $args);
  $content = $view->render();
}

```

# Answer
> 1 votes
You can use this code in custom block can also set permission.

```
 use Drupal\Core\Form\FormState;
 use Drupal\views\Views;
   $form = [];
   $view_id = 'blog_landing_page';
   $display_id = 'page_1';
   $view = Views::getView($view_id);
   if ($view) {
   $view->setDisplay($display_id);
   $view->initHandlers();
 $form_state = (new FormState())
  ->setStorage([
   'view' => $view,
   'display' => &$view->display_handler->display,
   'rerender' => TRUE,
   ])
   ->setMethod('get')
   ->setAlwaysProcess()
   ->disableRedirect();
   $form_state->set('rerender', NULL);
 $form = \Drupal::formBuilder()->buildForm('\Drupal\views\Form\ViewsExposedForm', $form_state);
    }

```

---
Tags: views, 8
---


title: Editing display of submission results

text:
# Question
Title: Editing display of submission results
I'm working on a Drupal 8 site, and I'd like to adjust how the results (/admin/structure/webform/manage/*form-name*/submission/*ID*/edit) display – the client doesn't want to see all of the fields and submission-related information (UUID, URI, etc.), and wants to see all of the form submission fields filled out here as well.

I see that there's an option for submission views, but I don't see a similar option that applies to the Edit tab. I also see there's a Webform Views Integration module, but that looks more like what I'd want if I wanted to put a view within a form.

Is there configuration I'm not seeing to adjust the submission edit screen, or a better method of reviewing submission details on a page whose display I can customize?

Thanks!

# Answer
> 1 votes
> Is there configuration I'm not seeing to adjust the submission edit screen

No, there is no config screen to customize this "edit" screen.

> the client doesn't want to see all of the fields and submission-related information (UUID, URI, etc.)

You can use hook\_form\_alter() in a custom module and remove the submission information section.

> and wants to see all of the form submission fields filled out here as well.

They should be already be filled out, unless the user left them empty. Make these fields required if they should be filled out.

> I also see there's a Webform Views Integration module, but that looks more like what I'd want if I wanted to put a view within a form.

In correct, this allows you to display the webform results in a View. This is exactly what you need, well if you want to make an alternate page that has that "edit" info.

Also, you could alter the Webform's edit route so it uses your Webform View instead, but you would lose the edit ability tho. Since the View just displays what was entered and is not a form.

---
Tags: 8, webforms
---


# Question
Title: Get pre-processed data from nested Paragraphs
I am new to Drupal and building a theme with Drupal 8 + PatternLab. Instead of printing the actual paragraphs, I just extract the data from the fields and pass it to the front-end twig modules. For example, I have a "Hero" paragraph with a nested "Video" paragraph. The "Hero" paragraph has a "Title" field and the "Video" paragraph has a "Video URL" field. The "Video URL" field is of type "Media", which would be a reference to an entity. Here is the template for the paragraph:

`// paragraph--hero.html.twig
{%
 include '@organisms/o-hero.twig'
 with {
 title: data.title,
 video_url: ???
 }
%}`

Here is the `THEME.theme`:

```
function THEME_preprocess_paragraph(&$variables) {
  foreach ($variables['content'] as $field => $fieldData) {
    if (isset($fieldData['#field_type'])) {
      $newField = preg_replace('/^field_/', '', $field);

      // text
      if (in_array($fieldData['#field_type'], ['string', 'string_long', 'text', 'text_long'])) {
        if ($fieldData['#is_multiple']) {
          $variables['data'][$newField] = array_map(function ($item) {
            return $item['value'];
          }, $fieldData['#items']->getValue());
        } else {
          $variables['data'][$newField] = $fieldData['#items']->getValue()[0]['value'];
        }
      }

      // link
      if (in_array($fieldData['#field_type'], ['link'])) {
        $link = $fieldData[0];
        $title = $link['#title'];
        $url = $link['#url']->toString();
        $target = $link['#options']['attributes']['target'] ?? null;
        // echo '<pre>'; var_dump($link); exit;
        if (!$fieldData['#is_multiple']) {
          $variables['data'][$newField] = [
            'title' => $title ? $title : null,
            'href' => $url ? $url : null,
            'target' => $target ? $target : null
          ];
        }
      }

      // image
      if (in_array($fieldData['#field_type'], ['entity_reference'])) {
        if (!$fieldData['#is_multiple']) {
          if (isset($fieldData[0]['#media']->field_media_image)) {
            $image = $fieldData[0]['#media']->field_media_image;

            $imageUri = $image->entity->uri->value;
            $imageUrl = file_create_url($imageUri);

            $variables['data'][$newField] = [
              'alt' => $image->alt,
              'sizes' => [
                'default' => $imageUrl
              ]
            ];
          }
        }
      }
    }
  }
}

```

This way I get the `data` variable with only the data I need in the front-end. But the problem is that when using a nested Paragraph, it won't go through the pre-process functions since it's not actually being rendered, only its data are being extracted. Now, I can access the "Video URL" media inside the "Video" paragraph, but it only gives back the Entity ID value, and it doesn't get populated with the actual Entity values so I can extract the video thumbnail / title / url.

I am not sure if I could explain this correctly, but I want to be able to access `content.field_video_paragraph` fields same way I access the main paragraph field `content.field_title`.

# Answer
I'd advice not to loop through the render array `content`, but go directly for the entity object, in your case `$paragraphObject = $variables['paragraph']`

Once you have the object, you can always query any data you want, to drill through a referenced/nested entity, use `->entity`:
`$paragaph->hostfield->first()->entity->field_whatever->value`

For paragraphs, you can also query upwards:
`$parentEntity = $paragraph->getParentEntity()`

The example above works similar for almost all entity templates like `node.html.twig` or `paragraph.html.twig` and actually wouldn't need any preprocessing at all, since the entity object is passed to Twig:

Most of the time you can use
`entity.fieldname.index.value`

E.g. for a simple plain text field:
`{{ paragraph.field_whatever.0.value }}`

For nested paragraphs or referenced entities you can use:
`{{ paragraph.hostfield.0.target_id }} /* only numeric ID of ref.ent. */`
`{% paragraph.hostfield.0.entity %} /* referenced entity object, can be queried again */`
`{{ paragraph.hostfield.0.entity.field_whatever.0.value }} /* field value of a nested paragraph */`

For your hero paragraph you could do something like

`{% include 'hero.twig' with { title: paragraph.field_title.0.value } %}`
> 3 votes

---
Tags: theming, paragraphs
---


# Question
Title: Getting form variables data into twig templates
I want to pass an array and a form to a template file, using this code.

```
public function buildForm(array $form, FormStateInterface $form_state) {
  $form['job_locations'] = $job_locations;
  $form['#theme'] = 'search_form';
  $form['#method'] = 'get';
  // Omissis
  return  $form;
}

```

The value of `$job_locations` is the following.

```
Array(
  [0] => Array(
    [city] => Singapore
    [count] => 5
  )
  [1] => Array(
    [city] => Toronto
    [count] => 3
  )
)

```

The content of the template file is the following.

```
{% for location in form.job_locations %}
  {% if location.city  %}
    <li data-original-index="0">
      <a tabindex="0" class="location-list-item" data-tokens="null" role="option" aria-disabled="false" aria-selected="false">
        <span class="text">{{ location.city }}</span>
      </a>
    </li>
  {% endif %}
{% endfor %}

```

Everything is shown correctly, but the code I am using causes these errors.

> User error: "count" is an invalid render array key in Drupal\Core\Render\Element::children()
> User error: "city" is an invalid render array key in Drupal\Core\Render\Element::children()

How can I avoid to get these errors?

# Answer
> 1 votes
Three possible solutions:

1. Valid render array

You get a valid render array by putting the content of `city` and `count` in `#markup` elements:

```
  'city' => [
    '#markup' => 'Singapore',

```
2. Form variable with a `#`

Or start the variable name with a hash, so that it is no longer considered to be a form element which needs to be rendered:

```
$form['#job_locations'] = ...

```

Twig:

```
{% for location in form['#job_locations'] %}
  ...
{% endfor %}

```
3. Separate template

Or create a custom template with a variable for the locations array to theme the list separately from the form:

```
$form['job_locations'] = [
  '#theme' => 'job_location_list',
  '#locations' => $job_locations,
];

```

---
Tags: 8, forms
---