title: Log in with email address only

text:
# Question
Title: Log in with email address only
I am looking for a concrete way to *only* allow logging in with email address only in Drupal 8.

I have seen Login Email and Login EmailUsername modules, but *both* still allow for username login as well as email.

I am looking only for email.

So far, I have come up with this in the interim - but something is not quite right. While I can trigger a form error, the form still submits and authentication is called. It should not submit if the entered value does not resemble an email address:

```
/**
 * Implements hook_form_FORM_ID_alter().
 */
function mymodule_form_user_login_form_alter(&$form, FormStateInterface $form_state) {
  $form['name']['#type'] = 'email';
  $form['name']['#title'] = t('Email Address');
  $form['name']['#description'] = t('Enter your email address.');
  $form['name']['#element_validate'][] = 'mymodule_login_validate_user';
  $form['pass']['#description'] = t('Enter the password that accompanies your email address.');
}

/**
 * Custom validation handler for the form login.
 *
 * @param $form
 * @param $form_state
 * @return bool
 */
function mymodule_login_validate_user(&$element, FormStateInterface $form_state) {
  $email_input = $form_state->getValue('name');

  if (!\Drupal::service('email.validator')->isValid($email_input)) {
    $form_state->setError($element, 'Please enter a valid email address.');
  }
}

```

I am also overriding the core `user.auth` service with my own - I will be generating usernames based on factors about the user (fetching information from a remote AMS).

Is there any way to avoid username in Drupal 8?

edit: Users cannot register on the Drupal site, and forgot password will be replaced with a link to the external AMS system.

# Answer
> 0 votes
It seems Login with Email only should solve that. At least worth a look how they managed to do that.

> This simple Drupal 8 module allows users to log in **exclusively** with their email address from the standard login form.
>
> **Setup:**
>
> Just enable the module.
>
> **Recommended Modules:**
>
> This module is based on the Login Email or Username module: https://www.drupal.org/project/login\_emailusername

---
Tags: 8, users
---


# Question
Title: Trim on "Rewrite Results" doesn't work as expected
In my website I have a view showing event names. They are set to trim on 47 letters, "Add an ellipsis " and "Trim only on a word boundary".

However, an event called

"XXX Concorso di composizione e arrangiamento per Orchestra jazz" going on three lines.

I tried different settings (I mean enable/disable the three options mentionted) but still I don't understand why the word "composizione" is going on a new line.

# Answer
> 2 votes
You are not using a monospace font, so trimming based on a certain number of characters will not guarantee that your text will not wrap. Think about this example: The string "WWWWW" will wrap when "lllll" may not because "W"s are wider than "l"s.

You should be handling this via CSS. You can either use a monospace font (all letters are the same width) and you can then rely on character count (just remember that people can individualize the font size in their browser so for those people you might be out of luck with this method) or you can use a overflow hidden to make sure that text doesn't appear to wrap to the third line. Something like:

```
.classname {
  font-size: 20px;
  line-height: 1.5em;
  max-height: 3.2em;
  overflow: hidden;
}

```

---
Tags: views
---


title: Test domain access module

text:
# Question
Title: Test domain access module
I have used the domain access module to create 2 domains that our business use, and I wanted to test them in the CI cycle. How do I test them in CI that they are active and each domain uses the correct theme?

# Answer
You can easily craft a test that uses CURL to hit your site using domainA and another curl request to hit your site using domainB. What I would do is make sure each theme contains its own favicon (even if the actual favicon is the same, duplicate the file and put a copy in each theme). Then you can just look at the path to the favicon in the result of your CURL and you'll see the name of themeA or themeB and voila. You know it worked (or didnt).
> 1 votes

# Answer
If I understand correctly, your only problem is that the CI system isn't accessible via the production domains, which point at the live system.

It sounds like the best way to do this would be to craft HTTP requests to the CI system directly, setting the appropriate HOST header each time.

(This could be done both manually eg. with a client like Postman, and automated as part of the CI tests.)
> 0 votes

---
Tags: theming, domain-access
---


# Question
Title: How to add taxonomy term reference field in a custom form
In the previous version of Drupal, it was possible to reference taxonomy tags in Drupal's forms using the following option:

```
'#autocomplete_path' => 'taxonomy/autocomplete/'.$vid,

```

However, in the Drupal 8, taxonomy term reference field has been removed in favor of Entity reference, more info here.

So, is there any alternative available?

# Answer
> 9 votes
Well, I have found the way in the change records. take a look at: https://www.drupal.org/node/2418529

Here is the example options for taxonomy fields:

```
'#type' => 'entity_autocomplete',
'#target_type' => 'taxonomy_term',
'#selection_settings' => [
  'target_bundles' => array($vid1, $vid2),
],

```

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


# Question
Title: How to theme one specific Views 3 exposed filter form template and HTML?
I know of two ways to theme views exposed filter forms in Views 3:

* Copy the file `views-exposed-form.tpl.php` in `sites/all/modules/views/theme` to your theme folder and edit the HTML directly
* Use `hook_form_alter` in your template file, for example:

.

```
   function yourtheme_form_alter(&$form, $form_state, $form_id) {
     switch ($form_id)  {
       case 'views_exposed_form':
         # do things to the array
       break;
     }
   }

```

My problem is, I have different exposed filters on different views, and these approaches both hit all exposed filters equally. There's also nothing about exposed filters templates in the Theme Information on the views edit page.

How can I target these to one specific exposed filter on one specific view?

Views 3 with Better Exposed Filters (BEF) module, Drupal 7.

# Answer
> 1 votes
## For the .tpl file

Views recognises files with names of the form `views-exposed-form--view_id--display_id.tpl.php`. You can also use less strict filenames of the form `views-exposed-form--view_id.tpl.php` or `views-exposed-form--display_id.tpl.php`.

While it's not addressed directly there, you can look up and copy-paste what these values should be by going to the view edit page, then Advanced \> Theme \> Information, then taking a suffix from an option under Display Output at the top.

For example, this is a view with machine name `products`, and I'm targeting its `page` display:

So the filename is `views-exposed-form--products--page.tpl.php`.

Other prefixes in the Display Output section can be used too, for example `views-exposed-form--products.tpl.php` would target all displays from the "products" view, including blocks or panel panes, while `views-exposed-form--page.tpl.php` would target all views pages.

## For template.php

You can put a condition on the form's HTML id, which is generated along similar lines, like this:

```
   function yourtheme_form_alter(&$form, $form_state, $form_id) {
     switch ($form_id)  {
       case 'views_exposed_form':
         if($form['#id'] == 'views-exposed-form-viewid-displayid'){
             # do things to the array
         }
       break;
     }
   }

```

Or potentially even `switch($form['#id']){}` \- but the original is written assuming you already have other uses of this hook based on `$form_id` for other forms.

Continuing with my previous example, it'd be `views-exposed-form-products-page`.

Note that this might need a different string if you've overwritten the form ID output anywhere, and there doesn't seem to be any way to target all displays short of something crude like `if(strpos($form['#id'], 'views-exposed-form-products') !== false){ }`

# Answer
> 0 votes
Should you need to render individual filter fields with custom html use the code below

`<?php print $widgets['FIELD_ID']->label; ?> //for field Label
<?php print $widgets['FIELD_ID']->widget; ?> //for field widget`

Your FIELD\_ID should be what you get in the bold html below :

`<div id="edit-flight-way-wrapper" class="views-exposed-widget views-widget-`**filter-field\_flight\_way\_value**`">`

---
Tags: 7, views
---


# Question
Title: Can't add instance of custom field type to entity
I have a custom field type that I'm trying to add to a custom fieldable entity. The entity works fine and I've added other fields to it, my problem is when I go to add an instance of my field to the entity, I get the following SQL error:

> There was a problem creating field Authors: Exception thrown while performing a schema update.
> SQLSTATE\[42000\]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'NOT NULL, PRIMARY KEY (entity\_id, deleted, delta, langcode), INDEX bundle' at line 9: `CREATE TABLE {myentity__field_myfield} ( bundle VARCHAR(128) CHARACTER SET ascii COLLATE ascii_general_ci NOT NULL DEFAULT '' COMMENT 'The field instance bundle to which this row belongs, used when deleting a field instance', deleted TINYINT NOT NULL DEFAULT 0 COMMENT 'A boolean indicating whether this data item has been deleted', entity_id INT unsigned NOT NULL COMMENT 'The entity id this data is attached to', revision_id INT unsigned NOT NULL COMMENT 'The entity revision id this data is attached to', langcode VARCHAR(32) CHARACTER SET ascii COLLATE ascii_general_ci NOT NULL DEFAULT '' COMMENT 'The language code for this data item.', delta INT unsigned NOT NULL COMMENT 'The sequence number for this data item, used for multi-value fields', field_myfield_target_uid INT unsigned NOT NULL COMMENT 'The user ID of the author', field_myfield_affiliation NOT NULL, PRIMARY KEY (entity_id, deleted, delta, langcode), INDEX bundle (bundle), INDEX revision_id (revision_id) ) ENGINE = InnoDB DEFAULT CHARACTER SET utf8mb4 COMMENT 'Data storage for myentity field field_myfield.'; Array ( )`

I've replaced my entity with `myentity` and my custom field type with `myfield` for the above. My schema definition for my field type is as follows:

```
/**
 * {@inheritdoc}
 */
public static function schema(FieldStorageDefinitionInterface
$field_definition) {

  $columns = [
    // List the values that the field will save. This
    // field will only save a single value, 'value'
    'target_uid' => [
      'type' => 'int',
      'not null' => true,
      'unsigned' => true,
      'description' => "The user ID of the author"
    ],
    'affiliation' => [
      'type' => 'varchar',
      'size' => 255,
      'not null' => true
    ]
  ];

  $schema = [
    'columns' => $columns,
    // 'indexes' => [
    //   'target_uid'
    // ],
    // 'foreign keys' => [
    //   'target_uid'
    // ],
  ];

  return $schema;
}

```

I've looked at other core field types for guidance but I can't see where I'm going wrong.

# Answer
> 2 votes
You’re confusing the required `length` property of a `varchar` field with the `size` property of a `text` field.

Replace `size` with `length` (or `varchar` with `text` if that makes more sense) and your code should start working.

---
Tags: 8, entities
---


# Question
Title: Custom form to modify only some fields of an EntityForm
I generated an Entity following this guide. Now I would like to create a custom form to modify only some fields inside a single entity. I was thinking to create an action inside the controller calling a new/custom form:

1. I created the routing file to open the form with the specified path (I know I can also create an action inside the controller to open the form with a custom template)
2. I created the form that extends the main EntityForm:

```
class DetailedForm extends CompleteEntityForm{
    public function getFormId() {
       return 'detailed_form';
    }

    public function buildForm(array $form, FormStateInterface $form_state){
        $form = parent::buildForm($form, $form_state);
        return $form:
    }
 }

```
3. I put some lines of code inside the functions getFormId(), buildForm(), validateForm() and submitForm().

But in the end the result is an error:

> Call to a member function getEntityTypeId() on null in \drupal\core\lib\Drupal\Core\Entity\EntityForm.php on line 79 #0 \drupal\core\lib\Drupal\Core\Form\FormBuilder.php(196): Drupal\Core\Entity\EntityForm-\>getBaseFormId()

Any suggestions?

# Answer
> -1 votes
Based on the comments on the question, I fixed my issue.

I created the routing path to call the controller:

```
mymodule.manage_detailed:
  path: '/mes-detailed/cp/{eid}'
  defaults:
    _controller: '\Drupal\mymodule\Controller\DetailedController::manageAction'
    _title: 'Detailed'
  requirements:
    _permission: 'access content'

```

Controller:

```
class DetailedController extends ControllerBase implements ContainerInjectionInterface {

public function manageAction($eid) {

    $entityForm = \Drupal::entityTypeManager()
        ->getStorage('main_entity')
        ->load($eid);
    $finalform =  $this->entityFormBuilder()->getForm($entityForm);

    $render['form'] = $finalform;

    $render['#theme'] = 'manage_detailed';
    return $render;

}

}

```

Then I put inside the template all the form with:

```
{{ form }}

```

Because using only some fields inside the template didn't allow to save data. And finally I create the submit function to define the redirect:

```
public static function manage_form_submit(&$form, &$form_state) {
        $url = \Drupal\Core\Url::fromUri('internal:/link-to-go');
        $form_state->setRedirectUrl($url);
    }

```

To call the submit function I used the alter form function inside the module file:

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

 //drupal_set_message($form_id); //to show id of the form

 if ($form_id == 'name_of_entity_form'){

    $form['name']['#type'] = 'hidden';
    $form['status']['#type'] = 'hidden';
    $form['new_revision']['#type'] = 'hidden';
    $form['revision_log_message']['#type'] = 'hidden';
    $form['field_n1']['#type'] = 'hidden';
    $form['field_n2']['#type'] = 'hidden';
    $form['field_email_']['#type'] = 'hidden';
    $form['field_nd']['#type'] = 'hidden';
    $form['actions']['delete']['#type'] = 'hidden';

    $form['actions']['submit']['#submit'][] = 'Drupal\mymodule\Controller\DetailedController::manage_form_submit';

  }
}

```

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


# Question
Title: How to save a checkbox config_object in the schema files?
We have a custom module with the following files. It is mainly used to store a list of content types that this configuration applies to. When saving the configuration, we get the following code.

How do we properly set the `mymodule.schema.yml` file to save the checkboxes?

Error Message. We also get the error message if we select `Basic Page` from the configuration.

> The website encountered an unexpected error. Please try again later.InvalidArgumentException: The configuration property mymodule\_enabled\_content\_types.article doesn't exist. in Drupal\Core\Config\Schema\ArrayElement-\>get() (line 76 of core\lib\Drupal\Core\Config\Schema\ArrayElement.php). Drupal\Core\Config\StorableConfigBase-\>castValue('mymodule\_enabled\_content\_types.article ', 'article ') (Line: 211)

**mymodule/config/schema/mymodule.schema.yml**

```
mymodule.settings:
  type: config_object
  label: 'My Module settings'
  mapping:
    mymodule_enabled_content_types:
      type: string
      label: 'Enabled Content types'

```

**mymodule/config/install/mymodule.settings.yml**

```
mymodule_enabled_content_types: ''

```

**mymoduleForm.php**

```
...
public function buildForm(array $form, FormStateInterface $form_state) {
  $config->$this->config('mymodule.settings');
  // Get all Content Types.
  $types = \Drupal::entityTypeManager()
    ->getStorage('node_type')
    ->loadMultiple();

  foreach($types as $type) {
    $content_types[$type->id()] = $type->label();
  }
  $form['mymodule_enabled_content_types'] = [
    '#type' => 'checkboxes',
    '#title' => $this->t('Enabled Content Types'),
    '#description' => $this->t('Define what content types will be enabled.'),
    '#default_value' => $config->get('mymodule_custom_variable'),
    '#options' => $content_types,
  ];
}

public function submitForm(array &$form, FormStateInterface $form_state) {
    // Retrieve the configuration
    $this->configFactory->getEditable('mymodule.settings')
      ->set('mymodule_enabled_content_types', $form_state->getValue('mymodule_enabled_content_types'))
      ->save();

    parent::submitForm($form, $form_state);
  }
}
...

```

# Answer
You are creating your checkbox options as an associative array of node type (bundle) IDs as keys and their labels as values.

When this form is submitted, checked checkboxes submit as `key => key`. So the stored information (I suppose 'rss\_url' in your question is intended to being 'mymodule\_enabled\_content\_types') is similar to:

```
mymodule_enabled_content_types:
  article: article
  page: page
  custom: custom

```

As the keys of the submitted values are unknown before submission, and the values clearly are strings, this is a **sequence** of strings (compare https://www.drupal.org/docs/8/api/configuration-api/configuration-schemametadata#properties). The correct schema definition is:

```
mymodule.settings:
  type: config_object
  label: 'My Module settings'
  mapping:
    mymodule_enabled_content_types:
      type: sequence
      label: 'Enabled Content types'
      sequence:
        type: string

```

After changing your schema definition and rebuilding your caches, your form submit handler should work just fine and the configuration being saved using its correct data types.
> 4 votes

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


title: Parse entity_embed module markup

text:
# Question
Title: Parse entity_embed module markup
I'm using Drupal 8.1.1 with Acquia's Lightning distribution. I need to be able to embed a media entity (a tweet, instagram post, youtube video, image, etc.) and then captured the resultant HTML output in a hook. However, $node-\>body-\>value just gives me a weird markup like this:

```
<drupal-entity data-align=\"none\" data-caption=\"\" data-embed-button=\"media_library\" data-entity-embed-display=\"entity_reference:entity_reference_entity_view\" data-entity-embed-settings=\"{"view_mode":"media_library"}\" data-entity-id=\"21\" data-entity-type=\"media\" data-entity-uuid=\"ea90ea95-6b7e-4e44-a1a6-4e7baabe3cb7\"></drupal-entity>\r\n"

```

And rendering the entity through the renderer service gives me the entire output of the node, rather than just the html equivalent of the aforementioned markup.

Is there any way to parse this output and get the actual HTML of the embedded entity?

# Answer
> 3 votes
The body contains tokens set when you press an embed button in ckeditor.

This raw body content is processed by this filter:

http://cgit.drupalcode.org/entity\_embed/tree/src/Plugin/Filter/EntityEmbedFilter.php

```
 public function process($text, $langcode) {
    $result = new FilterProcessResult($text);

    if (strpos($text, 'data-entity-type') !== FALSE && (strpos($text, 'data-entity-embed-display') !== FALSE || strpos($text, 'data-view-mode') !== FALSE)) {
      $dom = Html::load($text);
      $xpath = new \DOMXPath($dom);

      foreach ($xpath->query('//drupal-entity[@data-entity-type and (@data-entity-uuid or @data-entity-id) and (@data-entity-embed-display or @data-view-mode)]') as $node) {
        /** @var \DOMElement $node */
....

```

You would have to build a view mode in ui with only the body field or apply the filter in code.

# Answer
> 0 votes
I was able to get the entity embed markup converted to the desired HTML markup with the help of the last and correct answer **here**.

---
Tags: 8, media, acquia-cloud
---


# Question
Title: Show a link in a menu even if user has no access
I created a node/add/content-type menu link in my main menu, but it only shows to those who have access to it.

How could I show this to everyone, including anonymous users, and use http://drupal.org/project/r4032login for those who have no access?

# Answer
> 2 votes
Add to the menu a page with no access restrictions that contains the login form. (But still called "Add Content Type" or whatever it's currently called).

Using Rules, add redirects to node/add/content-type

* automatically redirects logged-in users
* automatically redirects anonymous once logged in from the above page

# Answer
> 1 votes
Just found the Menu item visibility module. Here is a quote about it (from the module's project page):

> ... exposes configurable and extendable visibility settings for menu links. For example, if you want to create a 'My account' link that points to /user, both anonymous and registered users have access to the /user path, so both will see the link, even if anonymous users do not technically have an account. Using this module will allow you to only have your 'My account' link visible to registered users, and hide it from anonymous users.

# Answer
> 0 votes
Create menu link with the same name for only guests, which leads for login page

# Answer
> 0 votes
I solved the same problem. It seems the only easiest way is to manually set the menu path as an absolute URL, ie. http://youdomain.com/***

# Answer
> 0 votes
With the help from fishfree and the menu token module we can use a link like "\[site:url-brief\]/node/add/article" to solve the problem.

---
Tags: routes, users
---


# Question
Title: Is the latest Drupal 7 core, 7.59, fully PHP 7 ready?
I just transferred a Drupal 7 installation to Debian 9 and when I try to connect to the site I get the error `PHP Fatal error: Cannot use "self" when no class scope is active in vars.module on line 39`.

There is a Drupal issue on it Upgrade to PHP7: Cannot use "self" when no class scope is active \[#2668622\], but it doesn't seem to be fully resolved and I am not sure which PHP7 version it works on.

The version of PHP currently on Debian 9 is **PHP Version 7.0.27-0+deb9u1**

The point is I am running the latest version (Drupal 7.59) on Ubuntu 16.04 whose PHP version is **PHP Version 7.0.30-0ubuntu0.16.04.1** and it runs without that error.

Are there versions of PHP 7 running on Debian 9 which work with latest unpatched Drupal 7.59, perhaps later ones like PHP 7.1 or PHP 7.2?

Maybe the bug only manifests in early versions of PHP 7.

**UPDATE**: It turns out that `vars.module` is from the contrib module Variable API and not part of core, and was only enabled to support the Textile module. Disabling it solved the problem.

# Answer
> 4 votes
For the most part, Drupal 7 core is compatible with PHP 7, however in some cases you might run into issues, depending on your specific website's configuration.

There is a meta issue on drupal.org that you can follow at https://www.drupal.org/project/drupal/issues/2656548

In addition, although most of the widely used modules are, not all contributed modules are compatible yet. The issue you linked is for a contributed module, not Drupal core.

Your best bet is to test your site and its particular modules on a development PHP 7 environment and then resolve any issues you find. Once you're happy that the site is functioning as it should, update your PHP version on your production server.

In my personal experience, with at least a dozen Drupal 7 sites of varying sizes, I have had no issues with Drupal 7 on PHP 7.0 or 7.1 but I have had a few issues with 7.2 when it was new (which may have been resolved by now).

In some cases I have had to apply patches that were already available in issue queues, but generally I've only had to update modules to the latest versions.

# Answer
> 3 votes
I think what you see is exactly what the Drupal 7 php requirements warns about:

> Because PHP 7 is the newest release, extra care should still be taken with it. See the Drupal 7.50 release notes and the PHP 7 discussion for more details. However anecdotal evidence from a variety of users suggests that Drupal 7 can be successfully used on PHP 7, both before and after the 7.50 release.

I personally have run Drupal sites that are currently live on php 7.0 and 7.1 latest versions and have never had a problem with server updating to newer php minor version at a later date.

Even though php 7 is not the latest (7.1 and 7.2 are out) you still have to be cautious running Drupal 7 with php 7.0 or 7.1 and extra care should be taken (from experience) at the contributed modules level as there is still lots of them not running properly on php 7. In most cases updating modules to latest releases is enough but in some cases compatibility patches can be found in the respective issue queues.

I believe Drupal 7 can't be run with php 7.2 as it has major changes from previous versions 7.0 and 7.1. At least I never succeeded in running it with 7.2 and I am not aware of any patches.

# Answer
> 2 votes
Drupal 7 development is about to reach PHP 7.2 compliance.

See this issue on drupal.org: Fully support PHP 7.2 in Drupal 7.

> php 7.2 now passes all 7.x core tests

---
Tags: 7
---


# Question
Title: Getting Node Field Values from Referenced Entity within a Paragraph
I'm trying to create a featured content paragraph type, however, I can't figure out how to grab anything from the referenced node that is in my entity reference. I don't see any twig documentation that covers this seemingly crucial task at all either.

Does anyone know of a way to call something like get\_node() within a twig template?

# Answer
> 1 votes
If you're doing this in a node template you could access it like so

```
{{ node.field_paragraph.entity.field_in_paragraph.value }}

```

Obviously replace field\_paragraph with the machine name of the paragraph field and field\_in\_paragraph with the machine name of the field inside the paragraph you want.

---
Tags: theming, paragraphs, entities
---


# Question
Title: Programmatically change block content on page render only
I have a situation where I want to change the content of a block on certain conditions, but not permanently.

I'm using a `theme_preprocess_block()` hook to change the content of the block, but it's not carrying through to the page render:

```
function MYTHEME_preprocess_block(&$variables) {

  if ( $variables['base_plugin_id'] == 'block_content'
    && $variables['attributes']['id'] == 'block-mycustomfooterblock' ) {

    $variables['content']['#block_content']->set('body', [[
      'value' => 'New Content',
      'format' => 'full_html',
    ]]);

```

Even after clearing caches, the block content doesn't get replaced with "New Content".

I added this line

```
$variables['content']['#block_content']->save();

```

However, that permanently saved the change to the block, which I don't want.

How can I alter the block content just for the page render?

# Answer
You should probably try

```
$variables['content']['body'][0]['#text']= "<strong>html content</strong>";

```

complete example

```
function THEMENAME_preprocess_block(&$variables) {
  if ( $variables['attributes']['id'] == "block-newblock" ) {
    $variables['content']['body'][0]['#text']= "<strong>html content</strong>";
    $variables['content']['body'][0]['#format']= "full_html";
  }
}

```
> 1 votes

# Answer
You could write a pre\_render function that gets called by hook\_block\_alter. So in your .module file, you might try this:

```
use Drupal\Core\Render\Markup;

function MYMODULE_block_view_alter(array &$build, \Drupal\Core\Block\BlockPluginInterface $block) {
    if ($block->getBaseId() === 'mycustomfooterblock') {
        $build['#pre_render'][] = '_MYMODULE_block_customfooter_prerender';
    }
}

function _MYMODULE_block_customfooter_prerender(array $build) {
    $build['content']['#markup'] = Markup::create('New Content');
    return $build;
}

```
> 0 votes

---
Tags: 8, blocks
---


# Question
Title: Rewrite output for view field only when certain condition is met?
1. You have a list with Views
2. It contains titles of nodes.
3. When clicked those titles redirects to the nodes.

How to make a condition that if e.g. a checkbox is selected in the node saying something like e.g. 'Don't link this to the original content, redirect it somewhere else instead', then overwrite the default path of that node title to something custom?

I found a module https://www.drupal.org/project/views\_conditional does it do what I'm trying to achieve?

So e.g. you have a list with 10 nodes titles, 9 of them links to its content, but 1 links somewhere else because it has a checkbox/term selected in the node's settings?

# Answer
> 1 votes
You can do this with the UI with some of my favorite Views trickery.

---

1. Go to your content type, click the Boolean field and change its `Off value` to `0`.
2. Create a new view and add the Title field twice. Rewrite the link for one of them, and **Exclude both from Display**.
3. Add your Boolean field to the view and..

a. Rewrite the title of this field: `[title]`

b. No Results behavior: `[title_1]`

c. Count the number 0 as empty: ✓

d. Hide rewriting if empty: ✓

---

Because you changed the Off value of the field to 0, you can make Views trigger the No Results Behavior for the field. I've just tested this and it works fine so ask if you have any trouble.

---
Tags: 7, views
---


# Question
Title: "Login to your account" form block not showing on frontpage when "View published content" is disabled for anonymous
I am new to Drupal 8 but not to Drupal ;

In Drupal 8, I enabled the "Login to your account" block in one of my regions :

But on the homepage, the block is not showing in the correct region, instead the login form appears in the "Main content" block (but on 404 pages, for instance, it works fine).

Please note that as it is a private website, I disabled the "View published content" for anonymous users, may it be related ? Maybe it triggers the login form in the main content block, thus deactivating the one in the other region ?

How to set up the login form block in the correct region, on my homepage ? Do I have to render the form in a template hook and then pass it to html.twig ou region.twig ?

Thanks in advance for your answers

For the comment reply :

There is nothing fancy with the theme, this is the generic page template, and the theme is quite empty, derivated from the Stable theme, in which I didn't find any noisy tampering. My gues is that the Core is rendering the form, thus hiding the block.

# Answer
> 0 votes
Digging into the user module, I found out that the function blockAccess inside core/modules/user/src/Plugin/Block/UserLoginBlock.php hides the block on the user.login page. Too bad, I had no homepage defined, so the default page was /user, and so the default route was ... user.login.

I guess I know what to do now: define a proper homepage, which will return a regular "403" that show the block.

Thanks again for your replies.

# Answer
> 0 votes
Drupal core does not support a good way to have a site that requires the user to log in.

The Require Login contrib module adds this functionality. It also allows for public sections of the site (e.g. a login landing page, links to how to get help, and the like.

---
Tags: forms, blocks
---


title: Trigger ajax action by url or link

text:
# Question
Title: Trigger ajax action by url or link
I currently have a page which has a block with taxonomy terms displayed. Each link has been made to work with ajax to display information below if clicked, generated in a module callback.

What I am trying to acheive is also have this work if linked to. So for example my page URL is currently http://localhost/events/building01 If someone was to visit http://localhost/events/building01/printer then the information for printer would be displayed under the taxonomy term as it would if someone had clicked on the term.

My ajax links are currently setup like:

```
function building_block_menu()
{
  $items['events/%/%/ajax'] = array(
  'title' => 'ajax call',
  'page arguments' => array(1, 2),
  'page callback' => '_event_ajax_callback',
  'access arguments' => array('access content'),
  'type' => MENU_CALLBACK,
  );
  $items['events/%/%/nojs'] = array(
  'title' => 'nojs call',
  'page arguments' => array(1, 2),
  'page callback' => '_event_nojs_callback',
  'access arguments' => array('access content'),
  'type' => MENU_CALLBACK,
  );
  return $items;
}
function _event_ajax_callback($building, $type)
{
  $markup = $building . ' - ' . $type;
  $ajax_commands = array();
  $ajax_commands[] = ajax_command_html('#ajax-target', $markup);
  ajax_deliver(array('#type' => 'ajax', '#commands' => $ajax_commands));
}
function _event_nojs_callback()
{
  return "no js to be built";
}

```

And called from links built like:

```
$output .= l($term->name, 'events/$building/'.$term->tid.'/nojs', array(
            'attributes' => array('id' => 'building-term-'.$term->tid, 'class' => 'use-ajax')
            ));

```

# Answer
The easiest option would be to add an ID to each link like `link_printer` and then use jQuery to parse the url, get the last fragment, and click any links that match.

```
var splitURL = window.location.href.split('/');
var link_id = '#link_' + splitURL[splitURL.length - 1];
if ($(link_id).length > 0) document.querySelector(link_id).click();

```
> 0 votes

---
Tags: ajax
---


# Question
Title: How to use profile2 profile type in custom form?
I'm building a multi step sign up form for my drupal 7 website, so I want to use one of profile type from profile2 in first step. For such purpose I'm using this code:

```
function personal_info_form($form, $form_state) {
    $form_state['profiles']['main'] = profile2_get_types('main');
    profile2_attach_form($form, $form_state);
    $form['#validate'][] = 'profile2_form_validate_handler';
    $form['#submit'][] = array('profile2_form_submit_build_profile', 'profile2_form_submit_handler');
    return $form;
}

```

But still getting error, you can visit this page to see the exact error http://dev.BlindHelp.net/user/register . Any help?

# Answer
i Suggest to use hook\_form\_alter or hook\_FORM\_ID\_form\_alter to perform specific task of existing form of profile2.

```
function mymodule_form_alter(&$form, $form_state, $form_id)  {
    switch ($form_id)  {
        case 'comment_form_id':
            $form['your_comment_form_name'] = array (
              '#type' => 'checkbox',
              '#title' => t ('Subscribe to replies to this comment'),
            );
            break;
        case 'user_register_form' :
           $form['actions']['submit']['#value'] = t('Submit');
           break;
     }
  }

```
> 0 votes

---
Tags: forms
---


# Question
Title: How to make a list of all nodes of content type ABC on a site (not a sitemap)?
I have a D8 website with about 100 landing pages for a Google Ads campaign. All of my landing pages are of content type **landing page**.

I want to make sure that the cache is primed for these pages because Google penalizes the site ("below average landing page experience") if it takes too long to load.

It seems like the standard approach to doing this is to run **wget** over your sitemap: https://swsblog.stanford.edu/blog/xml-sitemap-and-cache-priming

But, the landing pages aren't in my sitemap because they are too similar to each other. So, what should I do to get a list of the URLs of all of my landing pages?

# Answer
> 1 votes
Of course you can use Views (d'oh!) to do this.

Just make a view of content type **landing page** showing *fields* and then add a *link to content* and check the box for *show URL as text*.

---
Tags: caching
---


# Question
Title: Content sorted by machine name not title
I've drupal 8 configured on my server then I created content types. Now When I click Add Content on content page all the content types are sorted by machine name and not by their title.

For e.g I've following content types

Alert

Article

Basic Page

Category Landing Page

TimeLine

Events

Visual Navigation

Here all the items have same machine name except for Category Landing Page as it have machine name of "visual\_navigation\_landing" therefore when I click add content button on content page their I see the list as following

Alert

Article

Basic Page

TimeLine

Events

**Category Landing Page**

Visual Navigation

Here you can see "Category Landing Page" is at the bottom with visual navigation, can anyone help with this. I just want to sort this list by title and not machine name

Regards.

# Answer
> 0 votes
Just had to apply patch of "Content types are ordered by machine name on node/add"

https://www.drupal.org/project/drupal/issues/2693485

It resolved the issue

---
Tags: 8, nodes
---


# Question
Title: Custom Twig Template for Custom Content Type
In my custom modules I am creating a custom content type. I also need to apply a twig template for this custom content type, but I can't seem to get it to actually apply.

in myModule.module file I have:

```
function myModule_theme($existing, $type, $theme, $path) {

return [
    'faculty_bio_node' => [
      'variables' => [],
    ]
  ];
}

```

and I have a custom twig template named : faculty\_bio-node.html.twig

The content types machine name is faculty\_bio

# Answer
If you want to load the template from the module folder you are in the right hook, but you need to use the correct base hook. This means you have to start the template name with the base hook and a double underscore `node__` and declare the base hook in theme\_hook(), see Store template in module.

hook\_theme():

```
function myModule_theme($existing, $type, $theme, $path) {

return [
    'node__faculty_bio' => [
      'base hook' => 'node',
    ]
  ];
}

```

The Twig template path and name would then be `mymodule/templates/node--faculty-bio.html.twig`.
> 4 votes

# Answer
Drupal won't recognize the template using an underscore. Rather than using: **faculty\_bio-node.html.twig** Can you try **faculty-bio-node.html.twig**

Using this you can leave the return method for what it is.
> 0 votes

---
Tags: 8
---


# Question
Title: Twig template for two different instances of the system branding block
On the block layout page, I added the "Site Branding" block twice, once for normal use (all nodes except content type *landing page*) and once for landing page use (all nodes of content type *landing page*).

I themed the block using the twig template **block--system-branding-block.html.twig**, but this modifies both blocks.

Is there a way to get more specific and create a twig template for each block, or should I re-create the landing page block some other way so that I can use a different template?

**EDIT:** My goal is to actually change the HTML of the block, so I can't use a pure CSS approach.

# Answer
There's a few things you can do. Here's three.

1. Consider using a pure CSS approach. If you look at the body element for your page there may well be different classes you can use to make different selectors for styling the block. Modern CSS, particularly with the availability of :before and :after pseudo selectors, is incredibly powerful and you very often don't need custom HTML to adjust styling for different cases.
2. You can also implement hook\_theme\_suggestions\_alter in your theme (in the file `mytheme.theme`) to supply alternative template suggestions based on the current path, for example.

Following this example, your code might look like:

```
function THEME_NAME_theme_suggestions_block_alter(array &$suggestions, array $variables) {
  $current_path = \Drupal::service('path.current')->getPath();
  $result = \Drupal::service('path.alias_manager')->getAliasByPath($current_path);

  $path_alias = trim($result, '/');
  $path_alias = str_replace('/', '-', $path_alias);
  $path_alias = str_replace('-', '_', $path_alias);
  $id = $variables['id'];

  $suggestions[] = 'block__path_alias__'.$path_alias;
  $suggestions[] = 'block__' . $id . '__path_alias__'.$path_alias;
}

```
3. Another option would be to create a second variant of the site branding block then use the option in Drupal's block system which lets you turn blocks on or off by content type.
> 3 votes

# Answer
Try this module Block Content Machine Name

Will provide additional template suggestion like `block--block-content--[MACHINE_NAME].html.twig`.
> 1 votes

---
Tags: 8, blocks
---


title: How to create a dynamic front page

text:
# Question
Title: How to create a dynamic front page
I have created **page--front.html** in drupal 8 custom theme then how to make dynamic this page section ? where I write custom code. i.e. how to showing slider images to which is added in admin side.

Please suggest me which controller I use ?

# Answer
Your question is somewhat general but here is an attempt to make it a little more clear and answer it.

You can probably copy `core/themes/classy/templates/page.html.twig` to your theme's template directory and name it `page--front.html.twig` and you can modify it as you like.

**Perhaps a better approach** would be to do it in a modular way.

Find appropriate modules that give you desired functionality (slideshows etc) and most of them will allow you to create BLOCK(s) out of them and then you can add those blocks to any page you want but in your case it would be `<front>`.

Your front page could be made out of blocks from slideshow module and or views block(s) or even custom blocks (`/block/add`) or any other block.

Here is an example of how to set a block to display on front page

You can also create a basic page (or any content type) and then set it as front page by going to `Configuration > system > basic site settings > FRONT PAGE > Default front page` (admin/config/system/site-information). Blocks can still be placed on front page with this approach.
> 1 votes

---
Tags: 8, theming, page-controller
---


# Question
Title: How to grant only certain roles permissons over certain field?
I have a content type with a number of fields. But one of the fields in the edit form must be seen by administer and people with "Reviewer" role. How can i do it?

# Answer
Field permissions module now has a release candidate version for D8, this is the way to implement Role-based fine-grained control over fields.

When you enable that module edit the Content type fields you want custom permissions on, you will see a new option **Field visibility and permissions** where you can choose **Custom permissions**.

When you tick that option a table will appear listing Create, Edit and View permissions and all the Roles you have defined on the system. Add the Reviewer role to the ones who can Edit the field (Administrator is granted all by default), and adjust the other permissions as needed.

A new menu item will appear under Reports \> Fields \> **Report all field permissions** `/admin/reports/fields/permissions` where you can see all the Fields custom configuration in one place.
> 2 votes

---
Tags: 8, users
---


# Question
Title: Empty field value showing in webform email content
I have a file attach field in my webform. When i have submit my webform without this field,in my email content showing like "ATTACHED FILE: \[webform\_submission:values:attach\_file\]". I have checked "Exclude empty elements" in my email handler.This is working for all other fields in my form except this "File attach" field.How can i solve this issue?

# Answer
> 3 votes
Similar question was recently answered by the Webform module developer at drupal.org:

"You might just need to append the :clear prefix.

\[webform\_submission:values:element\_value\] =\> \[webform\_submission:values:element\_value:clear\]"

https://www.drupal.org/project/webform/issues/2982562

So, in your case use replacement pattern: \[webform\_submission:values:attach\_file:clear\]

---
Tags: 8, webforms
---


title: Formatting text below an image

text:
# Question
Title: Formatting text below an image
I'm a total newbie. I'm building a site which includes images, such as photographs, with text captions under them.

Recently (?!), some of these text captions have broken and slipped, with the first words appearing to the left of the image and the rest still below it where they should be. I've tried monkeying with the margin width, but that doesn't seem to be the problem.

Any clues?

# Answer
> 0 votes
There are many possible reasons how the code wound up being like that. If you could remove the inline styles for margins, height and width and instead add the class "img-responsive" to the image it would render in a more "standard" and expected way on the page. Alternatively you could add

```
width: 100%; height: auto;

```

to the inline style, but that would only be a "emergency" solution and not be considered good practice.

However it would probably be best to cleanup the markup so that the caption lives in a div or span with a class name of caption. Why are you not making use of the default caption option in Drupal? If you look at or install a "clean" version of Drupal 8 and create an article and add an image you can see how the caption works. It generates this markup:

```
<figure role="group" class="caption caption-img"><img alt="Dog" data-entity-type="file" data-entity-uuid="c8b30e3b-8346-4d2b-8df3-86dcff35d274" src="/sites/default/files/inline-images/images.jpeg"><figcaption>This is my nice caption</figcaption></figure>

```

---
Tags: media
---


# Question
Title: {{ language }} variable not available in block template
We are trying to generate a language dependent link in a custom block we created though the UI and placed it into a region.

If I `{{ dump(language) }}` in `page.html.twig`, I've got it there. But not in the block. Is this by design? Where/How can I get access to it?

# Answer
You can solve this with a preprocess hook:

```
mytheme_preprocess_block(&$variables) {
  $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
  $variables['language'] = $language;
}

```

The `language` variable will then be available in your block template as it is in the page one.
> 4 votes

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


title: unable to force JS library to HEAD

text:
# Question
Title: unable to force JS library to HEAD
I've read the main docs about this but find it lacking context. This did better job of explaining and it seems it should work. How to force a JavaScript library to load in the \<head\> of a Drupal 8 page EVERY attempt I try returns

```
A colon cannot be used in an unquoted mapping value

```

Searching for this, I've attempted to enclose the include line in single quotes, without, but all within context of attempting js-header

Since this YML, I'm making sure we're using two spaces for indentation and nothing else. What am I overlooking here? This is a snippet of mytheme.libraries.yml

```
  flexslider:
  version: 1.x
  css:
    theme:
      includes/flexslider/css/flexslider.css: {}
  js:
    includes/flexslider/js/jquery.flexslider-min.js: {}
  dependencies:
    - core/jquery

fontawesome:
  version: 1.x
  css:
    theme:
      includes/fontawesome/css/font-awesome.css: {}

global-styling:
  version: 1.3.2
  css:
    theme:
      includes/mapquest/css/mapquest.css: {}
  js-header:
    header: true
      js:
        includes/mapquest/js/mapquest.js: {}

```

This is portion of mytheme.info.yml that applies:

```
  #Libraries
  libraries:
  - mytheme/bootstrap
  - mytheme/flexslider
  - mytheme/fontawesome
  - mytheme/global-components
  - mytheme/global-styling

```

# Answer
I think you've indented too far. The line following `header: true` is directly beneath it in the example you linked to.

```
global-styling:
  version: 1.3.2
  css:
    theme:
      includes/mapquest/css/mapquest.css: {}
js-header:
  header: true
  js:
    includes/mapquest/js/mapquest.js: {}

```
> 2 votes

# Answer
Any root level declaration in your libraries.yml file of your theme need to be added via `#attached` in preprocess hooks, `{{ attach ...}}` in a Twig file, or globally by adding it to the theme info yaml:

```
  #Libraries
  libraries:
    - mytheme/bootstrap
    - mytheme/flexslider
    - mytheme/fontawesome
    - mytheme/global-components
    - mytheme/global-styling
    - mytheme/js-header

```

I'd also advise giving it a better name than 'js-header'.
> 1 votes

---
Tags: theming
---


# Question
Title: Use created year as condition in Entity Query
I'm performing an entity query that searches for nodes of my custom content type called 'news'. I want to perform the query in a way that only produces the 'news' nodes that have a Authored Date that fits within a specific date . Here is an attempt I made below. '

```
$year = 2018-02;
$query = \Drupal::entityQuery('node')
  ->condition('type', 'news')
  ->condition('created', [date('Y-M','created'), $year], '=')
  ->range(0, 10);

```

# Answer
> 6 votes
Try this function `get_nodes_by_authored_month_date('news', '2018-02')`

```

use Drupal\node\NodeInterface;

 /**
 * @param string $bundle_type
 * @param string $year_month
 *
 * @return array|int
 */
function get_nodes_by_authored_month_date($bundle_type = '' , $year_month = '') {

  $full_date = date_parse_from_format('Y-m', $year_month);
  //- Get number of days of month
  $number_of_days_of_month = cal_days_in_month(CAL_GREGORIAN, $full_date['month'], $full_date['year']);
  //- Get the timestamp of the first minute in the month
  $first_minute_of_month = mktime(0, 0, 0, $full_date['month'], 1, $full_date['year']);
  //- Get the timestamp of the last minute in the month
  $last_minute_of_month = mktime(23, 59, 59, $full_date['month'], $number_of_days_of_month, $full_date['year']);

  $query = \Drupal::entityQuery('node')
    ->condition('status', NodeInterface::PUBLISHED)
    ->condition('type', $bundle_type)
    ->condition('created', [$first_minute_of_month, $last_minute_of_month], 'BETWEEN')
    ->range(0, 10);

  return $query->execute();
}

```

---
Tags: database, datetime
---


# Question
Title: Invalidate a specific cache tag on any saved taxonomy term
I would like to clear cache tag of a particular bundle when any taxonomy terms are update/ saved.

I know the default node tag is saved like node:1, node:2, but I'm confused on how to invalidate a particular bundle.

# Answer
You don't invalidate entity tags, Drupal does this automatically on CRUD operations.

Instead add a cache tag to all nodes of the specific content type:

```
/**
 * Implements hook_preprocess_node()
 *
 */
function mymodule_preprocess_node(&$variables) {
  if ($variables['node']->getType() === 'my_content_type') {
    $variables['#cache']['tags'][] = 'taxonomy_term_list';
  }
}

```

The tag `taxonomy_term_list` gets invalidated on any taxonomy term saved/updated/deleted.
> 6 votes

---
Tags: 8, nodes, caching
---


# Question
Title: Which cache bin to clear after changing services
I made some changes to own services and now I get an error about invalid arguments. When I clear all caches everything works fine. I don't want to clear all caches in my production environment. Which cache bin (and how) do I need to clear? I use drupal console. I tried 'drupal cache:rebuild container' but I get a message 'Cache container is invalid'.

# Answer
> 2 votes
Drupal Console uses `Cache::getBins()` for its list of valid cache bins - that method returns all services in the main container tagged with `cache.bin`. The `container` cache service is part of the bootstrap container, which is managed internally by `DrupalKernel`.

I haven't dug deep enough to know for sure, but keeping the management of that bin internal seems to be deliberate, so there's probably no simple (maybe even no desirable) way to hack around it.

Fortunately, a custom plugin for Console is easy to create with `drupal generate:command` (there's a tutorial here). Just be sure to inject the `kernel` service, and call `$this->kernel->invalidateContainer();` in the command 's action callback.

# Answer
> 0 votes
There are no real guarantees about what needs to be invalidated when you change dependencies. The service definition for the compiled container doesn't match up with the PHP class constructors it is referencing, so you are getting errors. So, you need to do a full container rebuild, which will also trigger a cache clear.

The proper way to do this when pushing a change to a new environment is to add a an empty `hook_update_N()` to your module defining the service. It can also be done with an empty `hook_post_update_NAME`, which is what core tends to do to avoid patch conflicts (among other reasons).

Then, after deployment you can do a `drush updb`, which will run all pending updates.

---
Tags: 8, caching, console
---


# Question
Title: How to write phpUnit tests for hook_form_alter?
I have 1 function that is returning cancel form button. This function is in my .module file.

```
function _cancel_button(array &$form, FormStateInterface &$form_state) {
  // Adding buttons to cancel form.
  $form['actions']['cancel'] = [
    '#type' => 'submit',
    '#value' => t('Cancel'),
    '#access' => TRUE,
    '#submit' => ['redirectcallback'],
    '#limit_validation_errors' => [],
  ];
  return $form;
}

```

How to write PHPUnit test for this function? Is is possible to write a test for a function which is not enclosed in any class or don't have any namespace?

# Answer
It is technically possible to write a unit test for this. You'd need to manually require your `.module` file though.

It might be easier to use a `Kernel` test, as these will automatically load module files, fire hooks, etc.

```
MyTest extends KernelTestBase {

  /**
   * Modules to enable.
   */
  public static $modules = ['my_module'];

  /**
   * Test the function.
   */
  public function testCancelButton() {
    // The .module file will already be loaded, so you can call your custom function directly.
    $form = [...];
    _cancel_button($form, ...);
    // Now make assertions about expected changes.

```
> 4 votes

---
Tags: 8, testing
---


# Question
Title: How to log in a user and inspect their role in a functional test?
I want to write a functional test that takes some test user credentials in a remote system, and posts them to Drupal login.

So far, I have

```
  /**
   * These users should authetnicate via Netforum.
   */
  public function testNetforumUsersCanAuthenticate() {
    $this->drupalGet('user/login');
    $edit = ['name' => [redacted], 'pass' => [redacted]];

    $this->drupalPostForm(NULL, $edit, t('Log in'));
  }

```

The authentication *always* goes through the external system even if the local account exists in Drupal. Therefore, I cannot just create these accounts beforehand.

The account should get created when authentication passes - and then I want to look at the users roles to check if they match what I expect for the different test accounts.

What can I use to see that this was successful and then look at the roles and check them?

# Answer
> 1 votes
You should be able to load the user object using `user_load_by_name()`, and then just make your assertions:

```
$account = user_load_by_name('foo');
$expected_roles = [
  'foo',
  'bar',
];
$this->assertEquals($expected_roles, $account->getRoles());

```

As an aside, it may be worth pursuing a mocked/testing authentication service for your tests. This way they don't rely on an external service, and will be more stable and reliable.

---
Tags: 8, testing
---


# Question
Title: Missing Schema on custom field only during PHPUnit Test
I have a custom field setup that I created similar to this tutorial. I exported all my fields on my node to a test module and enable it during my PHPUnit test.

I run my test with the following command:

```
php ./core/scripts/run-tests.sh --verbose --php /usr/local/bin/php --url http://nginx --class "Drupal\my_module\Tests\ExpenseTest"

```

And I get the following error:

```
The test did not complete due to a fatal error.
Exception Uncaught e ConfigSchemaCheck   95 Drupal\Core\Config\Development\Conf
Drupal\Core\Config\Schema\SchemaIncompleteException: Schema errors for
core.entity_form_display.paragraph.my_field.default with the
following errors:
core.entity_form_display.paragraph.my_field.default:content.field_city_state.settings.size
missing schema,
core.entity_form_display.paragraph.my_field.default:content.field_city_state.settings.autocomplete_route_name
missing schema,
core.entity_form_display.paragraph.my_field.default:content.field_city_state.settings.placeholder
missing schema in
Drupal\Core\Config\Development\ConfigSchemaChecker->onConfigSave() (line
95 of

```

This is part of my core.entity\_form\_display.paragraph.my\_field.default.yml file:

```
field_city_state:
weight: 2
settings:
  size: '60'
  autocomplete_route_name: my_module.city_autocomplete
  placeholder: ''
third_party_settings: {  }
type: city_state_default
region: content

```

If I remove the settings it doesn't give me the error (Although I am not testing that field yet).

This is my module's Field Type Class:

```
<?php

namespace Drupal\my_module\Plugin\Field\FieldType;

use Drupal\Core\Field\FieldItemBase;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\TypedData\DataDefinition;
use Drupal\Core\Field\FieldItemInterface;

/**
 * Plugin implementation of the 'city_state' field type.
 *
 * @FieldType(
 *   id = "city_state",
 *   label = @Translation("City/State"),
 *   description = @Translation("An entity field containing city/state"),
 *   category = @Translation("Address"),
 *   default_widget = "city_state_default",
 *   default_formatter = "city_state_default"
 * )
 */
class CityStateItem extends FieldItemBase implements FieldItemInterface {

  /**
   * {@inheritdoc}
   */
  public static function schema(FieldStorageDefinitionInterface $field_definition) {
    return [
      'columns' => [
        'state_code' => [
          'type' => 'varchar',
          'length' => 2,
        ],
        'city' => [
          'type' => 'varchar',
          'length' => 255,
        ],
      ],
    ];
  }

  /**
   * {@inheritdoc}
   */
  public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
    $properties['state_code'] = DataDefinition::create('string')->setLabel(t('State Code'));
    $properties['city'] = DataDefinition::create('string')->setLabel(t('City'));

    return $properties;
  }

  /**
   * {@inheritdoc}
   */
  public function isEmpty() {
    $value = $this->state_code;
    return $value === NULL || $value === '';
  }

  /**
   * Get city string.
   *
   * @return string
   *   Returns city name.
   */
  public function getCity() {
    return $this->city;
  }

  /**
   * Get state code string.
   *
   * @return string
   *   Returns the state code.
   */
  public function getStateCode() {
    return $this->state_code;
  }

}

```

This is my module's schema file:

```
city_state:
  type: mapping
  label: 'City/State settings'
  mapping:
    state_code:
      type: string
      label: 'State Code'
    city:
      type: string
      label: 'City'

```

Don't understand why I am getting this error and only during Testing. (No issues when running config import on dev and staging).

# Answer
You only get that error during testing because the core testing base classes add a config schema checker during testing.

You have 2 options, the first is the easiest, but is not recommended, and that is to disable the strict config checking in your test by setting this variable to false in your test class:

```
  /**
   * Set to TRUE to strict check all configuration saved.
   *
   * @see \Drupal\Core\Config\Development\ConfigSchemaChecker
   *
   * @var bool
   */
  protected $strictConfigSchema = FALSE;

```

This approach is not preferred because you then have invalid config schema data in your module. It would be far better to fix the schema.

Instead of `city_state:` in your schema file, something more specific like:

```
field.field_settings.city_state:

```

or since this appears to be display related, it might be

```
field.formatter.settings.city_state:

```
> 6 votes

---
Tags: testing, configuration
---


# Question
Title: What configures Drupal to send emails on the create or update of an unpublished content?
My Drupal installation attempts to send emails to a number of users whenever I create or update content **but do not publish it**. But because sending email is not configured errors are generated.

I don't know what configuration item I could have deliberately or accidentally set to cause that. Is there any setting or module that could cause that?

I don't think I have configured any Rules or Workflow settings to send emails, and it only occurs when the item is unpublished

# Answer
> 0 votes
The culprit turned to be the Antispam module, which is the client for the Akismet anti-spam system.

Its default setting causes an email to be sent to some administrators whenever a module is updated.

What baffled me was why that setting applied only when an unpublished item was created or updated.

---
Tags: rules, emails, workflows
---


title: How to know when a field is a paragraph

text:
# Question
Title: How to know when a field is a paragraph
I'd like to know when a field from a node it's a paragraph, I only get the type, that it's entity\_reference\_revisions, I use this method to get the information:

```
\Drupal\field\Entity\FieldStorageConfig::loadByName()

```

But I'm not able to get this information

```
 [settings:protected] => Array
    (
        [target_type] => paragraph
    )

```

The only way I get it's to check directly to the database to see it the name of the field it's in the table paragraphs\_item\_field\_data.

Thanks

Oskar

# Answer
> 5 votes
You're probably looking for the EntityFieldManager service. It is available from the container as `entity_field.manager`. Its EntityFieldManager::getFieldDefinitions() method returns the field definitions for all fields that belong to a certain entity type **and bundle** (content type), keyed by their field names:

```
$definitions = \Drupal::service('entity_field.manager')->getFieldDefinitions('node', 'page');
if (
  isset($definitions['field_to_check'])
  && $definition = $definitions['field_to_check']
  && $definition->getSetting('target_type')
  && $definition->getSetting('target_type') == 'paragraph'
) {
  // Is a field of a 'node' entity, belongs to the bundle
  // 'page', has the 'target_type' property, and finally
  // references paragraphs.
}

```

If you load the field storage definition using FieldStorageConfig::loadByName() only, you need to be careful: Field definitions can be different for the various bundle (content) types. So you'd need to additionally check, whether your bundle (content type) matches the bundle of the node you are investigating the reference field for.

---
Tags: 8, entities, paragraphs
---


# Question
Title: Generate and email coupon code to customer after they purchase full price item
We have a situation where we want to be able to automate a process for certain customers to receive a discount coupon after making a purchase.

Ideally, customers could just throw two of whichever package they are purchasing into the cart and be good to go, but because of some oddities with our underlying product (a software package that they get access to for a few months) they need to make separate purchases if they need more than one license. And there are a few situations where we would want to provide a buy one get one half off coupon, but it's not every time.

I'm wondering if it's possible to create a condition of some sort, like a particular coupon code or product that we can provide to customers, that once they purchase an email is automatically sent with a 50% off your next purchase coupon.

I'm pretty new to working with Drupal and don't know where to start with this or if it's even possible.

edit: we are working in Drupal 7 and using ubercart

Thanks!

# Answer
> 0 votes
In Drupal just about anything is possible but you'll need to provide more context otherwise people won't answer you.

Drupal 7 or 8? Are you using Commerce or Ubercart?

In any case, the Rules module might be what you are looking for. It has the ability to act on different events.

---
Tags: ubercart
---


title: Adding alt text to a form field

text:
# Question
Title: Adding alt text to a form field
I know that alt text is usually used for images, to help screen readers etc. In this case my task manager wants me to add 'alternative text' to calendar items, to better satisfy 508 requirements. This would be for a custom content type called Event, which is called up in a view. The alt text would be entered by a user, and may or may not link to anything. I'm just trying to create a field that is wrapped in an alt tag, so it doesn't display but screen readers will find it. I've tried different things, such as adding dummy text into the .tpl file for calendar item, but I can't come up with a good variable for $title that works. I've tried using a php print statement in the .tpl but again, haven't found the right code. I'm thinking I will probably have to do surgery on the custom event module itself, which has a form for people to enter in the event data. One solution is to use hook\_form\_alter to add in some code, something like this:

`function events_form_alter(&$form_state, $form_id) {
 if ($form_id == 'events_form') {
 <?php print $title . "text"; ?>
 }
 }`

One thing is that I think the best place to find an event title variable is in an include file, where most of the module code lives. I can see #title being used in the include, but not sure what that is. A local variable? How can I use that variable to print in my alt text? I'm hoping I can use this variable in a hook\_form\_alter function that prints a statement using this title. From the include file:

```
    // Add an end and a date repeat form element, if needed.
if ($element ['#bundle'] == 'event') {
    if($element['#field_name'] == 'field_event_times_combined') {
        $element ['#title'] = t ( 'Date & Time' );
    }

```

But all this is close to exceeding my PHP skills, however. Does anybody have any general insight?

Many thanks

# Answer
I don't think your approach will work, adding the new "alt" field to the edit/add form is only a small part of the task. Where and how you save the data? Instead, create a new field via the manage field section. Then you can use theme\_preprocess or a tlp/twig file to change the output.
> 1 votes

---
Tags: forms
---


# Question
Title: The site is in a subdomain, but I get the wrong file path and a "require_once(): Failed opening required..." error
I have inherited a half ready development site, which I have to finish for the client. First I tried to backup and move to an other location, so I am sure that I can migrate the whole site. I moved the code to a subdirectory of one of the sites I manage, created a database and imported it from the old location. I also updated the settings.php with the proper database information. I tried to reach the site with "sitedomain.com/cicad" (cicad is the subdirectory name) and I get this error message.

> Fatal error: require\_once(): Failed opening required '/home/clients/*hashthag*/web-arvr/sites/all/themes/cicad/templates/\_menu-header-block.php' (include\_path='.:/opt/php7.0/lib/php') in /home/clients/*hashthag*/web-arvr/cicad/modules/php/php.module(80) : eval()'d code on line 2

The problem is that the proper path should start with /home/clients/*hashthag*/web-arvr/**cicad**/sites/. It doesn't include the SENTI subdirectory name in this path.

I have already tried:

* Setting *RewriteBase /cicad*
* Setting *DocumentRoot /home/clients/\_hashtag\_/web-arvr/cicad*
* Setting $base\_url to "domainname.com/cicad"
* Clearing the cache by Empty every cache\_\* table in the database.

Any idea what could be the problem?

# Answer
You may not use a subdirectory, but a subdomain instead, to have the site on the domain root (subdomains are often free and easy to configure in your hosting panel). This will prevent you from a lot of trouble when migrating from and to production.

The site is probably deducing paths from the drupal base path, which is incorrectly calculated in your setup (subdirectory), you will loose less time setting a "root domain installation" than looking for the errors in this site you don't know how to handle (yet).

The site is also probably hiding a lot of surprises, here the error comes from the "PHP" module, which should not happen on admin. There is probably some PHP inside blocks, which is not a good news.
> 1 votes

---
Tags: 7, migrations
---


# Question
Title: After module installation, updating translations still at 0%
I installed Drupal 8.5.6, in French. It seemed to work well, apart from no CSS working, but I corrected by unchecking CSS aggregation in the performance settings.

I decided to install some modules, one by one. Every time I install a module, after I click on the *Install* button, I get this.

>

After waiting more than 2 minutes (which is abnormal to me), I click on the *Extend* link to see if the module I am trying to install has been installed. The module seems to be installed, since it is checked, but it is not working.

So I uninstall that module, and try installing another module, but I get the same result.

Notice that the first modules I tried installing were the Coffee and Admin Toolbar modules. They get installed properly offline.

I have also noticed that using Drupal 8.2.5 everything is fine.

Is there any version problem, or am I doing something wrong?

I changed the PHP version using on the host to PHP 7.1.

# Answer
> 2 votes
After a few time doing something else, I went back to the issue. In fact a lot of **JavaScript** was not working correctly.

Then I decided to go back to **Configuration -\> Performance** and unchecked **JavaScript aggregator** and saved that configuration. See the image below :

**Now everything works fine**!!!

Now I can use **admin toolbar**'s dropdown menu as well as **coffee** and all the other stuff is working well.

**And thank you for reading me**.

---
Tags: i18n-l10n
---


# Question
Title: How do I add an image field to my node.tpl.php template using render($content['field_example'])?
I am creating a Bootstrap sub-theme and want to customize my node.tpl.php template. I have an image field with a machine name of 'field\_poster'. According to the default node template:

> $content: An array of node items. Use render($content) to print them all, or print a subset such as render($content\['field\_example'\]). Use hide($content\['field\_example'\]) to temporarily suppress the printing of a given element.

So, doesn't this mean I can add `print render($content['field_poster']);` to my node.tpl.php and it will output the image, right? Well, I've tried that and it does **nothing**!

How can I get my image field to render in my template?

## Update

My `field_poster` was set to display within a Field Group in *Display Settings*. This changes how things work in the template. See below for my solution.

# Answer
> 0 votes
Ok, so here was the problem. My `field_poster` was nested in a Field Group under display settings. Apparently, you need to include the parent field group if you want to render child fields outside the group.

So, if my container field group is named `group_fieldgroup1` I need to use the following to render my field:

`<?php print render($content['group_fieldgroup1']['field_poster']); ?>`

You can render the entire field group by using the following.

`<?php print render($content['group_fieldgroup1']); ?>`

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


# Question
Title: How to group view by field and display row results below?
We have a content type `Basic Page` that is supposed to be grouped by a taxonomy term field `Page Type` that has the following values below in a view.

How can we setup the view so that the view will display the `Page Type` in one group and the results in another group? Is this even possible without a `hook_preprocess_hook()` or custom `twig` template?

View Setup:

* Display: Block (\`block\_1')
* Format: Unformatted
* Format Setting: Grouping field nr. 1: `Page Type`, `User rendered output to group rows = true`
* Show: fields
* Show Settings: Inline fields --\> `Page Type`
* Fields: `Page Type`, `Title`, `field_description`
* Filter Criteria: `Published = true`, `Content type = Basic Page`
* Sort Criteria: `Page Type (asc)`

`Page Type` Values:

* Blog
* Press Release
* Video
* Document

Current results:

```
<section class="views-content">
  <div class="view-row">
    <div> Blog </div>
    <h3> Page Title1 </h3>
    <div> Continually negotiate bleeding-edge materials through installed.</div>
  </div>
  <div class="view-row">
    <div> Blog </div>
    <h3> Page Title2 </h3>
    <div> Collaboratively disseminate global customer service for..</div>
  </div>
  <div class="view-row">
    <div> Blog </div>
    <h3> Page Title3 </h3>
    <div> Continually evolve enterprise-wide total linkage through..</div>
  </div>
  <div class="view-row">
    <div> Press Release </div>
    <h3> Page Title4 </h3>
    <div> Energistically productize competitive sources after standards..</div>
  </div>
  <div class="view-row">
    <div> Video </div>
    <h3> Page Title5 </h3>
    <div>Professionally implement principle-centered portals without efficient..</div>
  </div>
  <div class="view-row">
    <div> Video </div>
    <h3> Page Title6 </h3>
    <div> Uniquely fabricate high-quality testing procedures with..</div>
  </div>
</section>

```

Desired results:

```
<section class="views-content">
  <div class="view-groups">
    <div> Blog </div>
    <div> Press Release </div>
    <div> Video </div>
  </div>
  <div class="view-row">
    <h3> Page Title1 </h3>
    <div> Continually negotiate bleeding-edge materials through installed.</div>
  </div>
  <div class="view-row">
    <h3> Page Title2 </h3>
    <div> Collaboratively disseminate global customer service for..</div>
  </div>
  <div class="view-row">
    <h3> Page Title3 </h3>
    <div> Continually evolve enterprise-wide total linkage through..</div>
  </div>
  <div class="view-row">
    <h3> Page Title4 </h3>
    <div> Energistically productize competitive sources after standards..</div>
  </div>
  <div class="view-row">
    <h3> Page Title5 </h3>
    <div>Professionally implement principle-centered portals without efficient..</div>
  </div>
  <div class="view-row">
    <h3> Page Title6 </h3>
    <div> Uniquely fabricate high-quality testing procedures with..</div>
  </div>
</section>

```

# Answer
> 3 votes
What you're trying to achieve isn't grouping by a field, it is displaying the same node list twice, showing different node information in the two instances.

You can achieve it by creating two Displays in your Views where one is showing only `Page Type` field, and the other is showing `Title` and `field_description` while sharing the same Filters.

If your original View is a Page Display, it makes sense to use Attachment Display for the other. You adjust the Attachment to appear Before or After the other Display results, depending on which you created first. You could also make one or both of them Block Displays and place them one below the other in the Content region of your theme.

You could also render one View Display into another Display Header, with the help of an additional module Views Field View.

Your HTML won't be exactly the same as in your question, but it will be close enough, and you can override the templates in your theme for those particular views displays to achieve exactly the output you want. Attachment views usually show with their own class and `view-row`s outside the `.views-content` of the Display they're attached to, but if you really need to you can override them and set your own classes.

## Drawing from Drupal 7 solution

I posted an answer to a similar question for Drupal 7: Filter a view by clicking on a link on another view. It doesn't completely mirror to D8 but with Better Exposed filters you can make an exposed filter behave similar to tabs, if you use Autosubmit optin and hide the Submit button.

## Taxonomy summary through a Contextual filter

One additional way of listing only the terms used on nodes in Views results is by creating a Summary through a Contextual filter.

1. On your Content Views Page add a Relationship to the `Page Type` field, you may require it since none of your results will have it empty.
2. Then add a Contextual filter **Term ID** from `Taxonomy term` Category and set it to use the Relationship from above, and these options:
`When the filter value is NOT in the URL`
**Display a summary**
**Descending**
**Number of records**
`Base path` (if this is not the first Page Display in your Views)
3. Add Attachment View Display to this Page, keep all the options the same as in Page, only override the Contextual filter and remove it from Attachment.

This way you get the original list of nodes, after the terms relevant to the results.

The terms are already sorted by the number of results tagged with it. To make the nodes in the Attachment sort the same way use Aggregation on it.

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


# Question
Title: Sharing the same templates by importing PHP files: Where should I store those PHP files?
I want to be able to just edit standard PHP files which are then imported into many themes.

I feel like a module is an overkill, so I'm happy with just a folder of files.

# Answer
Your question states "*I feel like a module is an overkill*", but (according to your own comment) the Domain ThemeKey module works perfectly for your use-case along with importing php files.

Some details about this module (from its project page):

> Integration of Domain Access and ThemeKey.
>
> Module provides additional ThemeKey properties:
>
> * domain:site\_name - returns current domain's site name
> * domain:id - returns current domain's id
> * domain:machine\_name - returns current domain's machine name
> * domain:is\_default - returns true if current domain configured as default domain
> * domain:is\_alias - returns true if system:host is an alias for current domain
> 0 votes

---
Tags: theming
---


# Question
Title: "Missing required paramter" with all Social Auth providers
The problem: I've just installed `social_auth_google`, `social_auth_twitter` and `social_auth_linkedin` modules. All the modules are configured (`Client ID`, `Client Secret`, and other similar fileds). The modules are installed through `composer require ...`, so I assume that all dependencies are there, but to confirm here's the list of the enabled modules:

`Social Social API (social_api) Enabled 8.x-2.0-beta4
 Social Social Auth (social_auth) Enabled 8.x-2.0-beta4
 Social Social Auth Google Enabled 8.x-2.0-beta3
 (social_auth_google)
 Social Social Auth LinkedIn Enabled 8.x-2.0-beta1
 (social_auth_linkedin)
 Social Social Auth Twitter Enabled 8.x-2.0-alpha2
 (social_auth_twitter)`

Besides these, composer also installed some non-Drupal packages to `vendor` directory:

* `league/oauth2-client (2.3.0)`
* `league/oauth2-google (2.2.0)`
* `abraham/twitteroauth (0.9.2)`
* `league/oauth2-linkedin (2.1.0)`

I've embedded "Social Auth Login" block to "Content" region of `/user/login` and `/user/register` pages, and I've got a decent-looking login/register pages as the result.

But the problem is that neither of the embedded authentication providers doesn't work. If I click g+, I get *"Error: invalid\_request. Missing required parameter: client\_id"*. When I click twitter, I get: *"You could not be authenticated, please contact the administrator."*. With LinkedIn I get: *"You need to pass the 'client\_id' parameter"*.

Obviously I'm missing something... Any help?

# Answer
For the sake of completeness, let me offer an alternative answer which will allow you to keep outgoing proxy in place.

After reviewing the code of both `social_auth_google` and `social_auth_linkedin`, I've concluded that they are both suffering from the same bug. And in both cases the bug is fixed in `2.x-dev` version. But dev version doesn't work because of some other issue (a missing class issue), so I couldn't migrate to dev. Instead I've kept their latest beta versions, and fixed the bug manually. I'll explain the fix on `social_auth_google` module, but the same thing should be done with `social_auth_linkedin` also.

The bug is in `social_auth_google/src/Plugin/Network/GoogleAuth.php` file, in `initSdk()` method. Here's the snippet with the bug:

`if ($this->validateConfig($settings)) {
 // All these settings are mandatory.
 $league_settings = [
 'clientId' => $settings->getClientId(),
 'clientSecret' => $settings->getClientSecret(),
 'redirectUri' => $this->requestContext->getCompleteBaseUrl() . '/user/login/google/callback',
 'accessType' => 'offline',
 'verify' => FALSE,
 'hostedDomain' => $settings->getRestrictedDomain(),
 ];`

````
// Proxy configuration data for outward proxy.
$proxyUrl = $this->siteSettings->get('http_client_config')['proxy']['http'];
if ($proxyUrl) {
    $league_settings = [
        'proxy' => $proxyUrl,
    ];
}

return new Google($league_settings);

````

`}`

What's happening there is that, if an outgoing proxy is defined, instead of adding `'proxy'` value to `$league_settings` variable, it overrides it completely. For this reason we don't have `'clientId'` defined anymore, thus getting the error from the original question: "Missing required parameter: client\_id".

So what we need to do is to simply change

`if ($proxyUrl) {
 $league_settings = [
 'proxy' => $proxyUrl,
 ];
 }`

with

`if ($proxyUrl) {
 $league_settings['proxy'] = $proxyUrl;
 }`

After this change, and the same exact change in `social_auth_linkedin` module, both authentication providers will work.
> 1 votes

# Answer
I've found the reason for the problem: outgoing proxy. The web server where I have my website installed doesn't have direct internet access, but it uses an outgoing proxy.

Regarding `social_auth_twitter` \- it was my mistake - outgoing proxy was blocking access to `api.twitter.com`. After configuring the proxy to allow this traffic - Twitter authentication started working as expected.

But regarding the other two (`social_auth_google` and `social_auth_linkedin`) - no requests ever reached the proxy, meaning that these modules *don't know* how to use the proxy.

I've ensured that the proxy is configured correctly:

* Environment variables `http_proxy`, `https_proxy`, `no_proxy`, `HTTP_PROXY`, `HTTPS_PROXY`, `NO_PROXY` are configured as needed;
* In `VirtualHost` element (Apache configuration) I'm ensuring that these environment variables are available by setting the appropriate `PassEnv` lines (`mod_env` module);
* `settings.php` file contains the appropriate `$settings['http_client_config']['proxy']['http']` (and other) configuration.

At the end of the day - everything else (installing and updating modules, etc.) is working normally through the proxy, so proxy configuration isn't the problem.

It looks that, at least for now, you cannot have `social_auth_google` and `social_auth_linkedin` if your web server is behind a proxy. Another very disappointing fact is that **there are no any logs** in `/admin/reports/dblog`, so you cannot know that modules are struggling to access their corresponding API endpoints. Hopefully it'll be resolved in future versions. For now **you simply have to allow direct access**, and remove outgoing proxy completely.
> 1 votes

---
Tags: 8, authentication-authorization
---


# Question
Title: display webform table data based on serial no
i want just like for example display hospital based on location webform data from webform storing data of all hospital.

How to fetch data from webforms table and display it on page just as searching the data based on specific field like name or location?

# Answer
> 0 votes
You can show this data using views module. Steps are below

1) Add new view and select in SHOW as webform submission Click continue and edit

2) In field section, add field as webform submission data:value, select webform node/formname and field you want.

In your example, hotel will be your form name and field name as name and location

---
Tags: webforms
---


# Question
Title: How to insert the title of the page as a class in page title block?
I am new to Drupal 8 theming and I've been long time trying the following:

I want to add classes to page-title in the template, `page-title.html.twig`. Two new classes:

1.- 'page\_title'

2.- The real title of the page

The code I'm using is,:

```
{{ title_prefix }}

{%
set classes = [
'page-title',
title|clean_class
]
%}

{% if title %}
<h1{{ title_attributes.addClass( classes ) }}>{{ title }}</h1>
{% endif %}

{{ title_suffix }}

```

it renders:

```
<h1 class="js-quickedit-page-title page-title array">FORMACIÓN: CURSOS Y  TALLERES</h1>

```

The string 'page-title' is working well but the variable title provoke an error:

> Notice: Array to string conversion in Drupal\Component\Utility\Html::getClass() (line 72 of core\lib\Drupal\Component\Utility\Html.php).

And print the class, array.

Any help?

# Answer
Seems `title` is a render array. You probably have to use `title.value` instead. But I'd recommend to simply preprocess that and leave the templates untouched.

You can implement `hook_preprocess_hook` and then use `TitleResolver::getTitle` and `Html::cleanCssIdentifier` to do what you want from inside your theme's `*.theme` file or from within a custom module's `*.module` file:

```
/**
 * Implements hook_preprocess_HOOK().
 */
function MYTHEME/MYMODULE_preprocess_page_title(&$variables) {

  // This won't work properly with Twig debugging enabled.
  // $title = $variables['title'];

  // Here is a safer method to get the current title.
  $request = \Drupal::request();
  $route_match = \Drupal::routeMatch();
  $title = \Drupal::service('title_resolver')->getTitle($request, $route_match->getRouteObject());

  $css_title = \Drupal\Component\Utility\Html::cleanCssIdentifier($title);
  $variables['title_attributes']['class'][] = 'page-title';
  $variables['title_attributes']['class'][] = strtolower($css_title);
}

```

---

You can use nearly the exact same snippet to add that CSS class to the `<body>` tag:

```
/**
 * Implements hook_preprocess_HOOK().
 */
function MYTHEME/MYMODULE_preprocess_html(&$variables) {

  $request = \Drupal::request();
  $route_match = \Drupal::routeMatch();
  $title = \Drupal::service('title_resolver')->getTitle($request, $route_match->getRouteObject());

  $css_title = \Drupal\Component\Utility\Html::cleanCssIdentifier($title);
  $variables['attributes']['class'][] = strtolower($css_title);
}

```
> 2 votes

---
Tags: theming, 8
---


# Question
Title: Not all fields of node are present in content
I've set up a custom content on my multilang site type with several fields that are all configured to be translatable. But when I try to theme that node I only habe a subset of the field available, although all the other field are saved in `fieldDefinitions` array. How to have all the fields available in `fields` array?

I have a node template `node--products.html.twig` Therein I access the values with `{{ content.field_content_rating_level }}` which works fine for the 4 fields in the fields array above, but not for the rest of theme even thought the share the same type of field. All fields are editable without any error in the backend. All fields are filled and translatable.

I use some of the missing fields in views and they work.

# Answer
The `{{ content }}` variable within node templates contains all fields configured to be visible within your content type's display settings. If you experience fields missing, they are most likely disabled within your display.

Head over to your administrative backend's `Structure > Content types > [Your content type] > Manage display` settings and ensure all fields you are trying to access are enabled for your current display mode.

You can always access disabled fields within your node templates by accessing the original node entity. The node entity along with its fields and some limited accessor methods are available within the `{{ node }}` variable of your templates.

Use e.g. `{{ dump(node|keys) }}` for debugging the available properties of the node within your template.

Comprehensive documentation about the variables within node templates can be found within it's header's comment block.
> 4 votes

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


title: How do I create a search page?

text:
# Question
Title: How do I create a search page?
I have the *Search API* and the *Solr search* modules installed. In /admin/config/search/search-api, I see my server and index created and with status set to *OK*. I can see on the index view page that my content is indexed correctly.

>

I did not use the *Solr Search Defaults* module because I have removed the default Article content type, and I don't want to recreate it. Without this content type, there is an error when activating the module.

How can I create a search page displaying all indexed results (for anonymous users, not in BO)?

One tutorial shows that *Solr Search Defaults* module uses views. I've created a view, where in *View settings \> Show* I've selected *Ideas* index. In the view, *Format \> Show* is set to *Rendered entity*. *Search index* is the view mode. I have a page, but no content is displayed. No filters are required, and all are exposed.

Other tutorial says I should create a search page in *Configurations \> Search and metadata \> Search pages* menu, but I don't have that menu.

---

Here are my *Fields* for Ideas index.  Here is another view I've tried, with *Show \> fields*  Here are my error logs, there is a Notice:  Here is what I see using `{{ kint(page.content) }}` on my Search results page:  If I create a view with *VIEW SETTINGS \> Show \> Content* my content IS diplayed correctly.

# Answer
After installing the searc api module:

1) goto: /admin/config/search/search-api/index/default\_index/edit

If you want for example to search for both Users & Content at once, make sure that both entities for Content & Users under the Data sources section are checked.

2) Goto: http://site8.dd:8083/admin/config/search/search-api/index/default\_index/fields

This page is used to choose which are the fields you want to be indexed for your search.

So make sure on this page that all the fields you want to search your entities by are added to your entities; If not, add any field using the **+Add Fields** button.

3) On the same page: http://site8.dd:8083/admin/config/search/search-api/index/default\_index/fields

Any field you add, it has its own data type which you have also the permission to change it.

As per the data type table available at the bottom of the page:

> Fulltext fields are analyzed fields which are made available for fulltext search. This data type should be used for any fields (usually with free text input by users) which you want to search for individual words.

so in your view, if you want to use the **Fulltext search** to search for your contents, every indexed field on this page should also be set to **Fulltext** data type.

4) Goto: http://site8.dd:8083/admin/config/search/search-api/index/default\_index

And make sure that the index Status bar is 100% and so all your contents are indexed to be searchable.

When you have done the above, create a new view as per below:

* Show: **index default content index**
* Check **Create page** box
* Display format **Grid**
* Hit **save and edit** button.

**Within the views configuration page:**

*Under add fields section:*

* add any fields you want and make sure the field title has the **(indexed field)** text.

*Under the filter criteria section:*

* add the **fulltext search** field and exposed to visitors.

Here you go, visit your search page and enjoy.

If none of the above helped you, feel free to ask any other question in comments or update your current question.
> 0 votes

---
Tags: search
---


# Question
Title: Issues with Composer at module dependencies
The Currency module requires Composer dependencies. I am trying to install it with the following command:

```
composer.phar require drupal/currency

```

It returns the following error.

> \[InvalidArgumentException\]
> Could not find package drupal/currency at any version for your minimum-stability (stable). Check the package spelling or your minimum-stability

What am I doing wrong?

Furthermore, if I specify the version of currency with `composer.phar require drupal/currency:8.x-3.1`, I get this error:

> \[UnexpectedValueException\]
> Could not parse version constraint 8.x-3.1: Invalid version string "8.x-3.1"

Anything is going wrong and I don't know what. The file composer.json and composer.phar are both in root directory of the Drupal installation.

# Answer
> 1 votes
`composer require drupal/currency:^3.0` should do it.

This will download the latest 3.x release version from Drupal.org. You don't specify the `8.x-3.1` in the version tag here, which is a confusing gotcha for people first starting with Composer. Composer already knows you are searching the 8.x releases because of the endpoint specified `/8`.

I suggest installing Composer also via https://getcomposer.org/doc/00-intro.md#globally instead of have the .phar in the Drupal project root.

As long as your root composer.json lists the Drupal packages endpoint, this command should work. If not, something else is wrong.

# Answer
> 3 votes
The error message could make you think there isn't any stable release of the module, but since there is a 8.x-3.1 version, that is not the case.

The possible causes are:

* `composer.phar require drupal/currency` is not executed from the directory containing the composer.json file you are using, or the one Drupal comes with
* The composer.json file doesn't list as repository the one having drupal/currency as package
* The repository listed from the composer.json file as the one containing the drupal/currency package is the wrong one
* The composer.json file is referring, in the repositories section, a server that is not anymore active, or where the packagist service has been disabled

Keep in mind that Composer, by default, looks at the packages in https://packagist.org. That is why the composer.json file that comes with Drupal 8.4 contains the following lines.

```
"repositories": [
    {
        "type": "composer",
        "url": "https://packages.drupal.org/8"
    }
]

```

If you were using https://packages.drupal.org/7 for Drupal 8, you would get the wrong modules. If you are using https://packagist.drupal-composer.org, that repository is not anymore working.

Keep also in mind that, if you were previously using https://packagist.drupal-composer.org, and you passed to https://packages.drupal.org/8, the package versions need to be accordingly changed; for example, using https://packages.drupal.org/8, `composer require honeypot:1.27` is requiring version 8.x-1.27 of the Honeypot module.

# Answer
> 0 votes
If you're getting an error like this the first time you use composer:

> \[InvalidArgumentException\]
> Could not find a version of package drupal/some\_project matching your minimum-stability (dev). Require it with an explicit version constraint allowing its desired stability.

...but there is definitely some version available that meets the criteria, and you get the same error on a well known project (e.g. `composer require drupal/views`), it's very likely the composer.json has a **missing or out of date repository**.

The docs on how to assign the correct repository should be in https://www.drupal.org/docs/develop/using-composer/using-composer-to-manage-drupal-site-dependencies but they are quite hard to find on that page, currently under the subheading **"Define Drupal.org as Composer repository if needed"** at the end of the long section **"Download Drupal core using Composer"**, which you might skip if you already have Drupal core downloaded and installed (e.g. if you use DrupalVM).

The necessary step is currently (August 2018) to run this command before using `composer require` for the first time. If it doesn't work, the repository location might have changed, so hunt for the appropriate section on the above-linked docs page:

```
composer config repositories.drupal composer https://packages.drupal.org/8

```

(substitute `7` for the `8` at the end if you're using Drupal 7)

---
Tags: 8, composer
---


# Question
Title: How do I remove the default node path when using a path alias?
When I add path aliases, how do I remove the system path (/node/\[nid\]) in Drupal 8, to avoid Google to index the page twice?

# Answer
> 5 votes
Simple answer: You don't have to. We pretty often are asked about disabling the generic URLs to avoid penalties from search engines.

This however is not necessary. Once using URL aliases, the meta tags for both versions of the node rightfully declare the `node/[nid]` paths as short URL, and the URL alias as canonical URL. So search engines will index the page using the URL aliases.

Penalties would arise only, if you provide the same content at various places and trying to disguise their connection.

If you still are afraid, you can e.g. make use of the rabbit\_hole module.

# Answer
> 3 votes
**We can either:**

Stop bots from indexing `/node/` by using robots.txt

**Or:**

Make Drupal 8 do 301 (permanently moved) redirect to the alias automatically by installing the Redirect module (no configuration is required).

---
Tags: 8, path-aliases
---


title: Rendered Entity not apearing under Show

text:
# Question
Title: Rendered Entity not apearing under Show
I created a new index and I've created a view with it but it only has the options to show as `Search Results` & `Fields`. Is there something that has to be done when configuring the index to get `Rendered Entity` to show up on views?

It does show up with the Default Content Index made with the module but whenever I make a new index and create a view with it isn't an option.

Pictures: What appears when creating a view with the default index(1) vs an index that I created(2).

# Answer
> 1 votes
Just figured it out. I found this. All I needed was to flush all caches.

---
Tags: views, 8, search
---